Arrays January 18 ,2026

Find All Triplets With Zero Sum (3Sum)

Problem Statement

You are given an integer array arr.

Your task is to find all unique triplets (a, b, c) such that:

a + b + c = 0

⚠️ The solution set must not contain duplicate triplets.

Example 1

Input

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

Output

[[-1,-1,2], [-1,0,1]]

Example 2

Input

arr = [0,1,1]

Output

[]

Example 3

Input

arr = [0,0,0]

Output

[[0,0,0]]

Why This Problem Is Important

  • One of the most asked interview questions
  • Builds foundation for 2-pointer technique
  • Teaches sorting + duplicate handling
  • Asked in FAANG, MAANG, product-based companies
  • Extension of Two Sum & Subarray problems

Approaches Overview

ApproachTechniqueTimeSpace
Approach 1Brute ForceO(n³)O(1)
Approach 2Hashing (Two Sum for each i)O(n²)O(n)
Approach 3Sorting + Two Pointers (Optimal)O(n²)O(1)

Approach 1: Brute Force

Idea

Check all possible triplets and store those whose sum equals 0.

Algorithm

  1. Loop i from 0 → n-3
  2. Loop j from i+1 → n-2
  3. Loop k from j+1 → n-1
  4. If arr[i] + arr[j] + arr[k] == 0, store triplet
  5. Remove duplicates manually

Time & Space Complexity

  • Time: O(n³)
  • Space: O(1) (excluding output)
     

C

#include 

int main() {
    int arr[] = {-1,0,1,2,-1,-4};
    int n = 6;

    for(int i=0;i

C++

#include 
using namespace std;

int main() {
    int arr[] = {-1,0,1,2,-1,-4};
    int n = 6;

    for(int i=0;i

Java

public class ThreeSum {
    public static void main(String[] args) {
        int[] arr = {-1,0,1,2,-1,-4};
        int n = arr.length;

        for(int i=0;i

Python

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

for i in range(len(arr)):
    for j in range(i+1, len(arr)):
        for k in range(j+1, len(arr)):
            if arr[i] + arr[j] + arr[k] == 0:
                print(arr[i], arr[j], arr[k])

JavaScript

let arr = [-1,0,1,2,-1,-4];
let n = arr.length;

for(let i=0;i

C#

using System;

class Program {
    static void Main() {
        int[] arr = {-1,0,1,2,-1,-4};
        int n = arr.Length;

        for(int i=0;i

Output

-1 0 1
-1 2 -1
0 1 -1

Approach 2: Hashing (Two Sum for Each Element)

Idea

Fix one element and solve Two Sum using a hash set for the remaining array.

Algorithm

  1. Fix index i
  2. Use a hash set to find pairs summing to -arr[i]
  3. Avoid duplicates

Time & Space Complexity

  • Time: O(n²)
  • Space: O(n)

Python

arr = [-1,0,1,2,-1,-4]
res = set()

for i in range(len(arr)):
    seen = set()
    for j in range(i+1, len(arr)):
        target = -arr[i] - arr[j]
        if target in seen:
            res.add(tuple(sorted([arr[i], arr[j], target])))
        seen.add(arr[j])

print(list(res))

Java

import java.util.*;

public class ThreeSum {
    public static void main(String[] args) {
        int[] arr = {-1,0,1,2,-1,-4};
        Set> res = new HashSet<>();

        for(int i=0;i set = new HashSet<>();
            for(int j=i+1;j temp = Arrays.asList(arr[i], arr[j], target);
                    Collections.sort(temp);
                    res.add(temp);
                }
                set.add(arr[j]);
            }
        }
        System.out.println(res);
    }
}

C++

#include 
using namespace std;

int main() {
    vector arr = {-1,0,1,2,-1,-4};
    set> res;

    for(int i=0;i seen;
        for(int j=i+1;j temp = {arr[i], arr[j], target};
                sort(temp.begin(), temp.end());
                res.insert(temp);
            }
            seen.insert(arr[j]);
        }
    }

    for(auto &v : res){
        cout << "[";
        for(int i=0;i

JavaScript

let arr = [-1,0,1,2,-1,-4];
let res = new Set();

for(let i=0;ia-b);
            res.add(JSON.stringify(triplet));
        }
        seen.add(arr[j]);
    }
}

let output = Array.from(res).map(x => JSON.parse(x));
console.log(output);

C#

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        int[] arr = {-1,0,1,2,-1,-4};
        HashSet res = new HashSet();

        for(int i=0;i seen = new HashSet();
            for(int j=i+1;j

Output

Unique triplets whose sum is 0:

[-1, -1, 2]
[-1, 0, 1]

Approach 3: Sorting + Two Pointers (Optimal)

Idea

Sort the array and use two pointers to find pairs for each fixed element.

Algorithm

  1. Sort the array
  2. Fix index i
  3. Use left = i+1, right = n-1
  4. Adjust pointers based on sum
  5. Skip duplicates

Time & Space Complexity

  • Time: O(n²)
  • Space: O(1)

Implementations

C++

#include 
using namespace std;

int main() {
    vector arr = {-1,0,1,2,-1,-4};
    sort(arr.begin(), arr.end());
    int n = arr.size();

    for(int i = 0; i < n; i++) {
        if(i > 0 && arr[i] == arr[i-1]) continue;
        int l = i + 1, r = n - 1;

        while(l < r) {
            int sum = arr[i] + arr[l] + arr[r];
            if(sum == 0) {
                cout << "[" << arr[i] << ", " << arr[l] << ", " << arr[r] << "] ";
                l++; r--;
                while(l < r && arr[l] == arr[l-1]) l++;
                while(l < r && arr[r] == arr[r+1]) r--;
            }
            else if(sum < 0) l++;
            else r--;
        }
    }
    return 0;
}

Python

arr = [-1,0,1,2,-1,-4]
arr.sort()
res = []

for i in range(len(arr)):
    if i > 0 and arr[i] == arr[i-1]:
        continue
    l, r = i+1, len(arr)-1
    while l < r:
        s = arr[i] + arr[l] + arr[r]
        if s == 0:
            res.append([arr[i], arr[l], arr[r]])
            l += 1
            r -= 1
            while l < r and arr[l] == arr[l-1]:
                l += 1
            while l < r and arr[r] == arr[r+1]:
                r -= 1
        elif s < 0:
            l += 1
        else:
            r -= 1

print(res)

JavaScript

let arr = [-1,0,1,2,-1,-4];
arr.sort((a,b)=>a-b);
let res = [];

for(let i=0;i0 && arr[i]===arr[i-1]) continue;
  let l=i+1, r=arr.length-1;

  while(l

Java

import java.util.*;

public class ThreeSum {
    public static void main(String[] args) {
        int[] arr = {-1,0,1,2,-1,-4};
        Arrays.sort(arr);
        int n = arr.length;

        for(int i=0;i0 && arr[i]==arr[i-1]) continue;
            int l=i+1, r=n-1;

            while(l

C#

using System;

class Program {
    static void Main() {
        int[] arr = {-1,0,1,2,-1,-4};
        Array.Sort(arr);
        int n = arr.Length;

        for(int i=0;i0 && arr[i]==arr[i-1]) continue;
            int l=i+1, r=n-1;

            while(l

Output

[-1, -1, 2]
[-1, 0, 1]

Summary

  • Brute force checks all triplets
  • Hashing improves to O(n²) but uses space
  • Sorting + Two Pointers is optimal & interview preferred
  • Duplicate handling is key interview discussion point

Next Problem in the Series

Kth Smallest Element in an Array

Sanjiv
0

You must logged in to post comments.

Related Blogs

Find the S...
Arrays February 02 ,2026

Find the Second Smal...

Find the S...
Arrays January 01 ,2026

Find the Sum of All...

Find the M...
Arrays January 01 ,2026

Find the Maximum Ele...

Find the M...
Arrays January 01 ,2026

Find the Minimum Ele...

Count Even...
Arrays January 01 ,2026

Count Even and Odd N...

Search an...
Arrays January 01 ,2026

Search an Element in...

Copy One A...
Arrays January 01 ,2026

Copy One Array into...

Reverse an...
Arrays January 01 ,2026

Reverse an Array

Print Alte...
Arrays January 01 ,2026

Print Alternate Elem...

Find the L...
Arrays January 01 ,2026

Find the Length of a...

Check if a...
Arrays January 01 ,2026

Check if an Array is...

Find the F...
Arrays January 01 ,2026

Find the First Eleme...

Find the L...
Arrays January 01 ,2026

Find the Last Elemen...

Count the...
Arrays January 01 ,2026

Count the Number of...

Replace Al...
Arrays January 01 ,2026

Replace All Elements...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at E...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at O...

Find the A...
Arrays January 01 ,2026

Find the Average of...

Count the...
Arrays January 01 ,2026

Count the Number of...

Remove Dup...
Arrays January 01 ,2026

Remove Duplicate Ele...

Move All Z...
Arrays January 01 ,2026

Move All Zeros to th...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by K...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by O...

Check if T...
Arrays January 01 ,2026

Check if Two Arrays...

Merge Two...
Arrays January 01 ,2026

Merge Two Sorted Arr...

Find Missi...
Arrays January 01 ,2026

Find Missing Number...

Find Dupli...
Arrays January 01 ,2026

Find Duplicate Eleme...

Count Freq...
Arrays January 01 ,2026

Count Frequency of E...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All U...
Arrays January 01 ,2026

Find All Unique Elem...

Insert an...
Arrays January 01 ,2026

Insert an Element at...

Delete an...
Arrays January 01 ,2026

Delete an Element fr...

Find the I...
Arrays January 01 ,2026

Find the Index of an...

Find Union...
Arrays January 01 ,2026

Find Union of Two Ar...

Find Inter...
Arrays January 01 ,2026

Find Intersection of...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s...

Find the L...
Arrays January 01 ,2026

Find the Largest Sum...

Kadane’s A...
Arrays January 01 ,2026

Kadane’s Algorithm (...

Two Sum Pr...
Arrays January 01 ,2026

Two Sum Problem

Subarray w...
Arrays January 01 ,2026

Subarray with Given...

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Rearrange...
Arrays January 01 ,2026

Rearrange Array Alte...

Leaders in...
Arrays January 01 ,2026

Leaders in an Array

Equilibriu...
Arrays January 01 ,2026

Equilibrium Index of...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s,...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All P...
Arrays January 01 ,2026

Find All Pairs with...

Longest Co...
Arrays January 01 ,2026

Longest Consecutive...

Product of...
Arrays January 01 ,2026

Product of Array Exc...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product Suba...

Find the F...
Arrays January 01 ,2026

Find the First Missi...

Count Inve...
Arrays January 01 ,2026

Count Inversions in...

Rearrange...
Arrays January 01 ,2026

Rearrange Array by S...

Check if A...
Arrays January 01 ,2026

Check if Array Can B...

Trapping R...
Arrays January 01 ,2026

Trapping Rain Water

Find Minim...
Arrays January 01 ,2026

Find Minimum in Rota...

Search in...
Arrays January 01 ,2026

Search in Rotated So...

Median of...
Arrays January 01 ,2026

Median of Two Sorted...

Merge Inte...
Arrays January 01 ,2026

Merge Intervals

Count Reve...
Arrays January 01 ,2026

Count Reverse Pairs

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Largest Re...
Arrays January 01 ,2026

Largest Rectangle in...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Rectangl...

Subarray S...
Arrays January 01 ,2026

Subarray Sum Equals...

Count Dist...
Arrays January 01 ,2026

Count Distinct Eleme...

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Maxim...

Find K Max...
Arrays January 01 ,2026

Find K Maximum Eleme...

Minimum Nu...
Arrays January 01 ,2026

Minimum Number of Ju...

Chocolate...
Arrays January 01 ,2026

Chocolate Distributi...

Kth Smalle...
Arrays January 01 ,2026

Kth Smallest Element...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Biton...

Find the S...
Arrays February 02 ,2026

Find the Second Larg...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com