How do you find a pair of elements with a given sum in an array?

DSA
Easy
142.8K views

This question asks candidates to identify two numbers in an array that add up to a specific target value efficiently. It tests knowledge of hash sets and the two-pointer technique for optimization.

Why Interviewers Ask This

Interviewers ask this to assess a candidate's ability to optimize space and time complexity beyond brute force solutions. They want to see if you can recognize patterns where a hash map reduces lookup time from O(n) to O(1). This problem also evaluates your understanding of trade-offs between using extra memory for speed versus keeping space complexity low. A strong answer demonstrates clear communication of algorithmic choices and edge case handling.

How to Answer This Question

Start by explaining the naive O(n^2) approach to show baseline understanding. Immediately pivot to the optimal solution using a hash set or sorting with two pointers. Clearly define the time and space complexity for both methods. Walk through a concrete example step-by-step to illustrate the logic. Finally, mention how you would handle duplicate values or negative numbers if the constraints change.

Key Points to Cover

  • Time complexity analysis of O(n) vs O(n^2)
  • Use of hash sets for constant time lookups
  • Handling edge cases like duplicates
  • Space complexity trade-offs

Sample Answer

The most efficient way is to use a hash set. As we iterate through the array, we calculate the complement needed to reach the target sum. If the complement exists in our set, we have found our pair. Otherwise, we add the…

Common Mistakes to Avoid

  • Forgetting to check for the complement before adding the current element
  • Not considering duplicate elements in the input array
  • Ignoring space complexity implications of using a hash map

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 questions