Explain how to solve the two-sum problem using a hash map (dictionary) in one pass.
💡 Model Answer
The two‑sum problem asks for two numbers in an array that add up to a target value. A one‑pass hash map solution runs in O(n) time and O(n) space. Iterate through the array, and for each element num at index i, compute its complement target - num. Check if the complement is already in the hash map. If it is, you have found the pair: return the indices of the complement and the current element. If not, store num and its index in the map and continue. This approach guarantees that each element is processed only once, eliminating the O(n²) nested loop. The hash map lookup is O(1) on average, so the overall time complexity is linear. Space complexity is also linear because in the worst case you store all elements. This algorithm is widely used in interview questions and real‑world scenarios where quick lookup of complementary values is needed.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500