How would you solve the Two Sum problem with optimal performance?

Coding
Easy
Infosys
89K views

This question is a staple for testing hash map usage and optimization skills. It requires finding two numbers that add up to a target value.

Why Interviewers Ask This

The Two Sum problem is frequently asked because it effectively tests a candidate's ability to trade space for time. It distinguishes between brute-force thinking and optimized approaches using hash maps. Interviewers want to see if you can identify patterns and utilize data structures to reduce complexity from quadratic to linear. It also serves as a gateway to more complex array and hashing problems in later rounds.

How to Answer This Question

First, mention the brute-force O(n^2) solution involving nested loops. Then, pivot to the optimal O(n) solution using a hash map. Explain how you store the complement (target minus current number) as a key and the index as the value. Walk through an example step-by-step to illustrate the lookup process. Emphasize that this allows for a single pass through the array.

Key Points to Cover

  • Hash map for O(1) lookups
  • Single pass algorithm
  • Storing complements instead of values
  • Time complexity reduction from O(n^2) to O(n)

Sample Answer

The optimal solution involves using a hash map to store elements as we iterate through the array. For each element, I calculate the difference between the target sum and the current element. If this difference exists in the hash map, I have found the pair, and I return their indices. Otherwise, I store the current element and its index in the map. This ensures that we only traverse the list once, resulting in O(n) time complexity. The space complexity is also O(n) due to the storage required for the hash map.

Common Mistakes to Avoid

  • Returning the values instead of indices
  • Using sorting which adds log n overhead unnecessarily
  • Failing to handle cases where no solution exists

Practice This Question with AI

Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.

Start Practicing

Related Interview Questions

Browse all 39 Coding questionsBrowse all 70 Infosys questions