/15. 3Sum

15. 3Sum

Medium
Arrays38.7% acceptance

Given an integer array arr, return all unique triplets [arr[x], arr[y], arr[z]] such that x, y, z are distinct indices and arr[x] + arr[y] + arr[z] == 0. The result must not contain duplicate triplets. The order of triplets and the order within each triplet does not matter.

Example 1

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

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

Explanation: Triplets [-2, 0, 2] and [-1, 0, 1] sum to zero.

Example 2

Input: [3, -3, 0, 0, 0]

Output: [[-3, 0, 3], [0, 0, 0]]

Explanation: Triplets [-3, 0, 3] and [0, 0, 0] sum to zero.

Example 3

Input: [1, 2, 3]

Output: []

Explanation: No triplet sums to zero.

Constraints

  • 3 <= len(arr) <= 3000
  • -105 <= arr[i] <= 105 for each i in arr
Python (current runtime)

Case 1

Input: [4, -4, 0, 2, -2]

Expected: [[-4, 0, 4], [-2, 0, 2]]

Case 2

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

Expected: [[-2, 0, 2]]

Case 3

Input: [5, -5, 0, 0, 0]

Expected: [[-5, 0, 5], [0, 0, 0]]

Case 4

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

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

Case 5

Input: [7, 8, 9]

Expected: []