int main() {
/* read in and sort array a */
int i=0,j=N-1, sum;
while ((sum = a[i] + a[j]) != tgt) {
if (sum < tgt)
i++;
else
j--;
}
printf("%d %d\n", i, j);
} int main() {
/* read in and sort array a */
int i=0,j=N-1, sum;
while ((sum = a[i] + a[j]) != tgt) {
if (sum < tgt)
i++;
else
j--;
}
printf("%d %d\n", i, j);
}Mostly, I just don't like the problem specification. What does it actually mean to "solve it efficiently"? How many times are we going to be searching each input array? How much memory do we have available? What tradeoff between memory and computation is allowable? How much does a comparison cost us versus accessing memory? Are all targets equally likely?
Assuming as theoretical computer scientists tend to do that we can ignore all constant time operations, that access to memory is free, that an unknown but fixed amount memory is available, and that we'll be searching the same array forever ruins the problem for me. Fill in the numbers and we can talk about what's optimal, but the "spherical cow" approach does nothing for me.
To your general point, sure, one thing that's nice (but takes a colossal effort) about Advent of Code is that it has specific inputs for players, and they have specific answers, so although it's usual for participants to write code which could (you hope) solve the problem in the abstract, the actual test is whether you solved the input you actually had. Sometimes not all conceivable inputs are even tractable (and some people find this situation frustrating if it happens) only the inputs given to real players may be suitable.
For this exercise the provided Go solution gets to handwave a bunch of problems. For example, Go's "map" hash table allocates whenever it wants to and has amortized table growth on top. That can really add up for a problem like this.
If I attacked it in Rust I would make HashMap::with_capacity(nums.len()) which does a single allocation up front, I might not need all this space if I exit early, but it won't hurt. I don't know if there's even a way to write that in Go.
Good point.
> You'd have to keep an additional mapping from the sorted to original positions.
It's simpler to just find the two numbers in the original unsorted array.
This is strictly more space efficient than a hash table. You're not going to win any awards for being cache efficient, but then again, when the competition is a damn hash table it's not too bad ;P
2*O(n) is still O(n)