Given an array of integers [20, 10, 5, 50, 0], find all unique pairs of numbers that sum to a target value (e.g., 9). Print each pair without duplicates.
💡 Model Answer
A simple and efficient way to find all unique pairs that sum to a target is to use a hash set. Iterate over the array, and for each element x compute its complement y = target - x. If y is already in the set, you have found a pair (x, y). Store the pair in a result list, ensuring you only add each unordered pair once (e.g., by always storing the smaller element first). After processing the element, add it to the set. This algorithm runs in O(n) time and O(n) space. For the example array [20, 10, 5, 50, 0] and target 9, the algorithm will find no pairs because no two numbers add up to 9. If the target were 15, the algorithm would return the pair (10, 5). This approach is straightforward, handles duplicates correctly, and scales well for large inputs.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500