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

DSA
Medium
116.1K views

This problem asks to identify two numbers in an array that add up to a specific target value. It tests your understanding of hash maps and two-pointer techniques for efficient searching.

Why Interviewers Ask This

Interviewers ask this to evaluate a candidate's ability to optimize space and time complexity. They want to see if you can move beyond the naive O(n^2) brute force solution. The question specifically probes knowledge of using auxiliary data structures like hash sets to achieve O(n) time complexity. It also assesses how well you handle edge cases such as duplicate elements or arrays with no valid pairs.

How to Answer This Question

Start by explaining the brute force approach to show baseline understanding. Then, pivot to the optimal solution using a hash set to store seen elements. Walk through the logic of checking if the complement exists before adding the current element. Discuss the trade-offs between time and space complexity. Finally, mention handling edge cases like empty arrays or single-element inputs to demonstrate robustness.

Key Points to Cover

  • Use a hash set for O(1) lookups
  • Iterate once through the array
  • Calculate complement dynamically
  • Handle edge cases explicitly

Sample Answer

To solve this efficiently, I would use a hash set to track elements we have already visited. As we iterate through the array, for each number, we calculate its complement by subtracting it from the target sum. If the com…

Common Mistakes to Avoid

  • Using nested loops resulting in O(n^2)
  • Forgetting to check for duplicates
  • Not handling empty input arrays

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