CodingReported in a candidate post, Jul 2025
Find pairs in an unsorted array that sum to S
Filed under VMware
Free read 2 of 3Use a set to store seen numbers. Iterate through the array, check if (S - current) exists in the set. If yes, a pair is found.
The question
Given an unsorted array of integers and a target sum S, return all unique pairs (a, b) such that a + b = S.
Constraints
- Array length can be up to 10^5.
- Integers can be negative.
- Pairs should be unique.
Examples
- Input
- nums = [2, 7, 11, 15], S = 9
- Output
- [(2, 7)]
- Why
- 2 + 7 = 9.
Approach
Use a set to store seen numbers. Iterate through the array, check if (S - current) exists in the set. If yes, a pair is found.
Sort the array first. Use two pointers (left and right) to find pairs that sum to S in O(n log n) time.
If unique pairs are required, use a set to store found pairs or skip duplicates during iteration.
Solution
O(n) time, O(n) space
def find_pairs(nums, S):
seen, pairs = set(), set()
for x in nums:
target = S - x
if target in seen:
pairs.add(tuple(sorted((x, target))))
seen.add(x)
return list(pairs)
Tips
- What they are testing: Test with empty arrays, arrays with no pairs, and arrays with duplicate values.
- Common mistake: Using a nested loop approach which results in O(n^2) time complexity.
Related VMware questions
Collected from public candidate posts and coding forums. Updated Nov 2026.