by fractionalhare · 6y ago · 0 comments
>>> Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice.
Seems trivial enough to me... except if the interviewer forgets the hard constraint that there is exactly one solution, then that's a shitstorm of edge cases.
I'd criticize the problem for asking for the positions of the numbers rather than the numbers. That's just super annoying for no reason.
If you can create a new array containing indices to the original array, sort the new array, and use two pointers starting at the beginning and the end of the sorted array to find a solution, it takes O(n×log(n)) time. It is not necessary to assume that the solution is unique, assuming it is okay to simply write one of the possible solutions.
If all values are between 1 and k, and you can make a k-sized array, you can find a solution in O(n+k).
No matter what you do, you can't get better than O(n).
The important thing is that there is more than 99% chance you will never have to solve this problem in your job; and even in the case you would, there is 95% chance that the O(n×log(n)) solution would be acceptable regardless of whether it is the best possible or not.
I guess you've been giving candidates a more hardcode version of the problem, not having that constraint?
edit: nevermind, it's the other poster who was giving that problem, not you. No idea how they formulate it in their interviews.
I was asked the two sum problem in an interview once, but I forget if it had this constraint or not. This seems much more reasonable.
Yeah, you just do it in O(n²) worst case because the problem is O(n²) to find all pairs that match because there can be O(n²) pairs.
However he meant one pair here too. Pretty easy to solve. Did it in under 30 s in Python on my broken cellphone. If there are multiple pairs, just replace return with yield.