3 Sum Problem

3 Sum Problem

3 Sum Problem Statement

Given an integer array arr of size n, find all magic triplets in it.

Magic triplet is a group of three numbers whose sum is zero.

Note that magic triplets may or may not be made of consecutive numbers in arr.

Example

{
"arr": [10, 3, -4, 1, -6, 9]
}

Output:

["10,-4,-6", "3,-4,1"]

Notes

  • Function must return an array of strings. Each string (if any) in the array must represent a unique magic triplet and strictly follow this format: "1,2,-3" (no whitespace, one comma between numbers).
  • Order of the strings in the array is insignificant. Order of the integers in any string is also insignificant. For example, if ["1,2,-3", "1,-1,0"] is a correct answer, then ["0,1,-1", "1,-3,2"] is also a correct answer.
  • Triplets that only differ by order of numbers are considered duplicates, and duplicates must not be returned. For example, if "1,2,-3" is a part of an answer, then "1,-3,2", "-3,2,1" or any permutation of the same numbers may not appear in the same answer (though any one of them may appear instead of "1,2,-3").

Constraints:

  • 1 <= n <= 2000
  • -1000 <= any element of arr <= 1000
  • arr may contain duplicate numbers
  • arr is not necessarily sorted

We have provided two solutions.

3 Sum Solution 1: Brute Force

A simple solution is to use three nested loops and check for each possible combination if their sum is zero. To avoid duplicate answers, we need to hash the triplet and store it in a set. An easy way to hash a triplet is by converting it to a string.

Extra space needed will be the number of unique triplets that contribute to the answer.

Time Complexity

O(n3).

Auxiliary Space Used

O(1).

Space Complexity

O(n2).

Code For 3 Sum Solution 1: Brute Force

    /*
    * Asymptotic complexity in terms of size of `arr` `n`:
    * Time: O(n^3).
    * Auxiliary space: O(1).
    * Total space: O(n^2).
    */
    static ArrayList<String> find_zero_sum(ArrayList<Integer> arr) {
        Set<String> answer = new HashSet<>();
        // Sorting is only necessary for avoiding duplicates in the answer.
        Collections.sort(arr);
        int n = arr.size();
        for (int index_1 = 0; index_1 < n; index_1++) {
            for (int index_2 = index_1 + 1; index_2 < n; index_2++) {
                for (int index_3 = index_2 + 1; index_3 < n; index_3++) {
                    int sum = arr.get(index_1) + arr.get(index_2) + arr.get(index_3);
                    if (sum == 0) {
                        answer.add(arr.get(index_1) + "," + arr.get(index_2) + "," + arr.get(index_3));
                    }
                }
            }
        }
        return new ArrayList<>(answer);
    }

3 Sum Solution 2: Optimal

This solution uses the Two Pointers Technique. We maintain left and right pointers to elements of a sorted array. If their sum is greater than intended we decrease the right pointer, otherwise we increase the left pointer. This method works in linear time, and to solve this particular problem we use this algorithm n times, once for each element in arr.

First, we will sort arr, that will contribute O(n * log(n)) to the time complexity. Then, for every element or arr, we will apply the two pointer technique to find any magic triplets that include that element. We will then add unique triplets to the answer.

Time Complexity

O(n2 + n * log(n)).

Auxiliary Space Used

O(1).

Space Complexity

O(n2).

Code For 3 Sum Solution 2: Optimal

    /*
    Asymptotic complexity in terms of size of the input array `n`:
    * Time: O(n^2 + n * log(n)).
    * Auxiliary space: O(1).
    * Total space: O(n^2).
    */

    static ArrayList<String> find_zero_sum(ArrayList<Integer> arr) {
        Set<String> answer = new HashSet<>();
        Collections.sort(arr); // A prerequisite for the two pointer technique to work.
        int n = arr.size();
        for (int index = 0; index < n; index++) {
            int currentElement = arr.get(index);
            // We will look for two elements that sum up to this:
            int neededSum = -currentElement;
            int left = index + 1, right = n - 1;
            while (left < right) {
                int sum = arr.get(left) + arr.get(right);
                if (sum == neededSum) {
                    answer.add(currentElement + "," + arr.get(left) + "," + arr.get(right));
                    left++; // "right--" would also work fine here.

                    // Note that the three numbers in our magic triplet strings
                    // will always be sorted in the increasing order because
                    // we sorted the array and because index > left > right.
                    // That and using a set to store the strings is enough for
                    // avoiding duplicates in the answer.
                } else if (sum > neededSum) {
                    right--;
                } else {
                    left++;
                }
            }
        }
        return new ArrayList<>(answer);
    }

We hope that these solutions to the 4 sum problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.

If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart’s FREE webinar to understand the best way to prepare.

Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.

We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:

‍To learn more, register for the FREE webinar.

Try yourself in the Editor

Note: Input and Output will already be taken care of.

IK courses Recommended

Master ML interviews with DSA, ML System Design, Supervised/Unsupervised Learning, DL, and FAANG-level interview prep.

Fast filling course!

Get strategies to ace TPM interviews with training in program planning, execution, reporting, and behavioral frameworks.

Course covering SQL, ETL pipelines, data modeling, scalable systems, and FAANG interview prep to land top DE roles.

Course covering Embedded C, microcontrollers, system design, and debugging to crack FAANG-level Embedded SWE interviews.

Nail FAANG+ Engineering Management interviews with focused training for leadership, Scalable System Design, and coding.

End-to-end prep program to master FAANG-level SQL, statistics, ML, A/B testing, DL, and FAANG-level DS interviews.

Select a course based on your goals

Agentic AI

Learn to build AI agents to automate your repetitive workflows

Switch to AI/ML

Upskill yourself with AI and Machine learning skills

Interview Prep

Prepare for the toughest interviews with FAANG+ mentorship

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Almost there...
Share your details for a personalised FAANG career consultation!
Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!

Registration completed!

🗓️ Friday, 18th April, 6 PM

Your Webinar slot

Mornings, 8-10 AM

Our Program Advisor will call you at this time

Register for our webinar

Transform Your Tech Career with AI Excellence

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

25,000+ Professionals Trained

₹23 LPA Average Hike 60% Average Hike

600+ MAANG+ Instructors

Webinar Slot Blocked

Interview Kickstart Logo

Register for our webinar

Transform your tech career

Transform your tech career

Learn about hiring processes, interview strategies. Find the best course for you.

Loading_icon
Loading...
*Invalid Phone Number

Used to send reminder for webinar

By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!
Registration completed!
🗓️ Friday, 18th April, 6 PM
Your Webinar slot
Mornings, 8-10 AM
Our Program Advisor will call you at this time

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Your PDF Is One Step Away!

The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants

The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer

The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary