/15. 3Sum

15. 3Sum

Medium
Arrays38.7% acceptance

Given an integer array arr, return all unique triplets [arr[a], arr[b], arr[c]] such that a, b, and c are distinct indices and arr[a] + arr[b] + arr[c] == 0. The solution set must not contain duplicate triplets. The order of triplets and the order of elements within each triplet does not matter.

Example 1

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

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

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

Example 2

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

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

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

Example 3

Input: [4, 5, 6]

Output: []

Explanation: No triplet sums to zero.

Constraints

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

Case 1

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

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

Case 2

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

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

Case 3

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

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

Case 4

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

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

Case 5

Input: [7, 8, 9]

Expected: []