Two Sum - Find Two Elements Summing to a Target
viaGlassdoor
Problem: Given an array of integers and a target value x, find two elements in the array that sum to x, in O(n) time using a single pass.
Constraints: Return as soon as a valid pair is found (or all pairs, depending on the exact ask).
Example: arr = [2,7,11,15], x = 9 -> (2,7).
Approach: Use a hash set - iterate through the array once; for each element a, check whether (x - a) already exists in the set of previously seen elements. If yes, a pair is found. Otherwise add a to the set and continue. O(n) time, O(n) space, single pass.
asked …