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 complement exists in our set, we have found our pair. This approach allows us to solve the problem in linear time, O(n), which is significantly better than the nested loop approach. We simply return the indices or values of the two numbers once identified.

Common Mistakes to Avoid

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

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 49 DSA questions