Indeed, the solution proposed by the interviewer will suffer from overflow. In fact, there is a better solution that does not suffer from overflow, which might have followed the interviewer if you suggested summing.
The best solution is much less intuitive, but as far as I know, it is pretty well known these days.
He relies on the following:
x xor y = y xor x x xor 0 = x x xor x = 0
Thus, the best solution involves computing xor of all given numbers, and then xoring with xor of all numbers from 1 to n . Those that appear in your array will be canceled with tags from 1 to n . One that was absent will remain.
As for how to think about such solutions, there is no recipe. You just need to be familiar with such questions about problems / interviews and have some background in computer science and math.
Do not feel too bad not to get it. I almost certainly wouldn’t get the summation solution in setting up the interview if I hadn’t seen the problem before graduating from college (maybe I understood this at the time), and I definitely wouldn’t come up with an xor solution without seeing it in the first place. These questions are pretty much hit or missed. And if it's a blow, they will probably ask for something else until you know the answer.
They do not do this to catch you. They do this to see how you think about it, as a rule: you can come up with a naive solution (you made), can you say what is wrong with him? can you figure out how to improve it, maybe with a little push in the right direction? can you explain how you are going to research the best solution? The thought process may be more important than the decision.
If the whole interviewer said that your decision is bad and you should have the best, best solution (I don’t think there is a checklist of things that you should absolutely know about X after finishing major in X), you should look for the best place to work .