3 Sum
Determine if there exists three elements in a given array that sum to the given target number. Return all the triple of values that sums to target.
Assumptions
The given array is not null and has length of at least 3
No duplicate triples should be returned, order of the values in the tuple does not matter
Examples
A = {1, 2, 2, 3, 2, 4}, target = 8, return [[1, 3, 4], [2, 2, 4]]
Solution: left right pinch at every index
Iterate through array
only check for first appearance of each element
for each element check for (x + y = target - element)
If found:
add (element, x, y) to results
skip trailing duplicate x, continue searching
Time Comp: Two iterations O(N^2)
Space Comp: O(N) result storage
Last updated
Was this helpful?