Return Unique Three-Sum Value Triples
GoogleSoftware Engineer · OnsiteLast updated
Return all unique value triples that reach a target using three distinct input positions, with canonical ordering despite duplicate values. Candidates are evaluated on duplicate control, overflow-safe sums, nonmutation, output-sensitive complexity, and careful boundary cases.
Return Unique Three-Sum Value Triples
Problem
Implement threeSumTarget(nums, target) -> triples.
Return every distinct value triple [a, b, c] for which three distinct input indices exist, a <= b <= c, and a + b + c == target.
Each value triple must appear exactly once even when the input contains duplicates. Sort the returned triples lexicographically. Return [] when no triple exists, and do not mutate nums.
Constraints
0 <= nums.length <= 2,000.-1,000,000,000 <= nums[i], target <= 1,000,000,000.- Use signed 64-bit arithmetic for sums.
- Target
O(n^2 + P)time after sorting, wherePis the number of returned triples, andO(n + P)space including the result.
Examples
nums = [-1, 0, 1, 2, -1, -4]
target = 0
triples = [[-1, -1, 2], [-1, 0, 1]]
nums = [2, 2, 2, 2]
target = 6
triples = [[2, 2, 2]]
nums = [1, 2]
target = 3
triples = []
Discussion Requirements
- Explain how duplicate values are skipped without losing a valid repeated-value triple.
- Compare the quadratic approach with extending the hash-based two-sum strategy for each fixed first element.
Hints
Hint 1
Separate index use from output identity: Trace an input containing four copies of one value and decide which repeated index choices collapse to the same canonical value triple.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.