What is the optimal approach to solve the Two Sum problem?

DSA
Easy
Infosys
93.8K views

Candidates must find two numbers in an array that add up to a target. This tests hash map usage and lookup efficiency.

Why Interviewers Ask This

The Two Sum problem is a fundamental interview question to assess data structure knowledge. Interviewers want to see if the candidate knows how to use a hash map to achieve O(n) time complexity instead of O(n^2). It also checks their ability to handle edge cases and return indices correctly.

How to Answer This Question

Describe iterating through the array and checking if the complement (target minus current number) exists in a hash map. If it does, return the stored index and current index. Otherwise, store the current number and its index in the map. Emphasize the trade-off between time and space.

Key Points to Cover

  • Hash map storage
  • Complement calculation
  • Single pass solution
  • Index retrieval

Sample Answer

The optimal solution involves using a hash map to store numbers and their indices as we iterate. For each number, I calculate the complement needed to reach the target. If the complement exists in the map, I have found t…

Common Mistakes to Avoid

  • Using nested loops
  • Forgetting to store indices
  • Handling duplicate numbers incorrectly

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 127 DSA questionsBrowse all 149 Infosys questions