As asked
You are building a product feature that needs to find pairs of items in a user's data list that together meet a target value, for example matching two expense line items that sum to a budget target. Implement a solution and explain the time and space complexity tradeoffs, including why you would not reach for a brute-force nested loop in a user-facing feature.
Sample answer outline
Use a hash map to store each value and its index as you iterate. For each element, check if target minus that element exists in the map. This runs in O(n) time and O(n) space. The brute force O(n^2) solution with nested loops is worth mentioning as the naive approach to contrast.
Reference implementation (typescript)
function twoSum(nums: number[], target: number): number[] {
const seen = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (seen.has(complement)) {
return [seen.get(complement)!, i];
}
seen.set(nums[i], i);
}
return [];
}Expect these follow-ups
- How does your solution change if the array is sorted and you want O(1) space?
- How would you return all pairs, not just the first?