How do you solve two sum efficiently?easy
Answer
Use a hash map to store values you have seen and check whether the complement exists.
Explanation
For each number x, compute target - x. If that complement is already in the map, you found the pair. This reduces the brute-force O(n^2) approach to O(n) time with O(n) extra space.
Hint: reason from constraints before calculating.
Follow-upHow would the solution change if the input array is sorted?