Given an array of integers nums and an integer target, return an array of arrays containing all unique triplets that add up to target.
Each returned triplet must be in ascending order, and the final result must not contain duplicate triplets.
You may assume nums has at least 3 elements.
Example:
Input:
nums = [-1, 0, 1, 2, -1, -4]
target = 0
Output:
[[-1, -1, 2], [-1, 0, 1]]
This is a generalized version of the classic 3Sum problem.
The optimal strategy:
- Sort the array
- Fix the first element using index
i - Use a two-pointer approach (
landr) to find pairs that sum totarget − nums[i] - Carefully skip duplicates for:
- the fixed index
i - the left pointer (
l) - the right pointer (
r)
- the fixed index
Time complexity is O(n²); sorting helps deduplicate easily and ensures the triplets are sorted.
The VOprep team has long accompanied candidates through various major company OAs and VOs, including Tesla, Google, Amazon, Citadel, SIG, providing real-time voice assistance, remote practice, and interview pacing reminders to help you stay smooth during critical moments. If you are preparing for these companies, you can check out our customized support plans—from coding interviews to system design, we offer full guidance to help you succeed.