Blind 75
10 / 75Free practice

3Sum

Medium · Two pointers

Jump to code

Return every distinct triplet of values in an integer array that sums to zero. A triplet uses three different indices; duplicate value-triplets should appear once.

Examples

Example 1

nums = [-1,0,1,2,-1,-4]

Output: [[-1,-1,2],[-1,0,1]]

Example 2

nums = [0,1,1]

Output: []

Constraints

  • 3 <= nums.length <= 1000
  • -10^5 <= nums[i] <= 10^5
Need a hint?

Fix one value, then solve a sorted two-sum problem.

Asked in real interviews

Candidates reported versions of 3Sum from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 9 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    -1,
    0,
    1,
    2,
    -1,
    -4
  ]
]
Expected
[
  [
    -1,
    -1,
    2
  ],
  [
    -1,
    0,
    1
  ]
]
Case 2
Input
[
  [
    0,
    1,
    1
  ]
]
Expected
[]
Case 3
Input
[
  [
    0,
    0,
    0
  ]
]
Expected
[
  [
    0,
    0,
    0
  ]
]
Case 4
Input
[
  [
    -2,
    0,
    1,
    1,
    2
  ]
]
Expected
[
  [
    -2,
    0,
    2
  ],
  [
    -2,
    1,
    1
  ]
]
Case 5
Input
[
  [
    -1,
    -1,
    -1,
    2,
    2
  ]
]
Expected
[
  [
    -1,
    -1,
    2
  ]
]

Drafts are saved per language in this browser when storage is available.