Coding questions · NVIDIA
Find all unique triplets summing to zero
This question evaluates array-based algorithm design, handling of duplicate results, and analysis of time and space complexity when producing unique triplets that sum to zero.
Problem
Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] such that:
i,j, andkare distinct indices (i != j != k), andnums[i] + nums[j] + nums[k] == 0.
The returned triplets must be unique (i.e., no duplicate triplets in the output). Triplets can be returned in any order.
Input
nums: an array of integers
Output
- A list/array of unique triplets, each triplet containing three integers whose sum is zero
Constraints (typical interview bounds)
0 <= nums.length <= 3000-10^5 <= nums[i] <= 10^5
Example
- Input:
nums = [-1, 0, 1, 2, -1, -4] - Output:
[[-1, -1, 2], [-1, 0, 1]]
Find All Unique Triplets Summing to Zero
Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] such that i, j, and k are distinct indices and nums[i] + nums[j] + nums[k] == 0.
To make the output deterministic, return each triplet in non-decreasing order, and return the full list of triplets in lexicographic order. Do not include duplicate triplets.
Hints
- Sorting the array helps you avoid duplicates and makes it possible to use a two-pointer scan.
- Fix one number, then look for two remaining numbers whose sum equals its negation.