3 Sum

Asked atAckoHHashedInSprinklr
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given an integer array nums. Return all triplets such that:

  • i != j, i != k, and j != k

  • nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets. One element can be a part of multiple triplets. The output and the triplets can be returned in any order.

Input: nums = [2, -2, 0, 3, -3, 5] Output: [[-2, 0, 2], [-3, -2, 5], [-3, 0, 3]] Explanation: nums[1] + nums[2] + nums[0] = 0 nums[4] + nums[1] + nums[5] = 0 nums[4] + nums[2] + nums[3] = 0

Input: nums = [2, -1, -1, 3, -1] Output: [[-1, -1, 2]] Explanation: nums[1] + nums[2] + nums[0] = 0 Note that we have used two -1s as they are separate elements with different indexes But we have not used the -1 at index 4 as that would create a duplicate triplet

Input: nums = [8, -6, 5, 4] (Give answer with the output and triplets sorted in ascending order)

  • 1 <= nums.length <= 3000
  • -104 <= nums[i] <= 104

cpp

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        
    }
};

java

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        
    }
}

python

class Solution:
    def threeSum(self, nums: list) -> list[list]:

javascript

class Solution {
    threeSum(nums) {

    }
}

csharp

public class Solution {
    public IList<IList<int>> ThreeSum(int[] nums) {
        
    }
}

go

func threeSum(nums []int) [][]int {

}
Stuck? Show a way to structure it+
  1. 01Sort the values and fix each possible first element once.
  2. 02Search the remaining suffix with left and right pointers.
  3. 03After finding a triplet, skip duplicate values at all three positions.
  4. 04Use sorted-order bounds to stop early when no later triplet can sum to zero.

Reference answer

Then expect these follow-ups

  • How would you generalize this to k-sum?

    Tests: recursion pattern

  • Why can the scan stop when the fixed value is positive?

    Tests: sorted reasoning

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question