Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close

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.

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.

Worried About Failing Tech Interviews?

Attend our free webinar to amp up your career and get the salary you deserve.

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Accelerate your Interview prep with Tier-1 tech instructors
blue tick
360° courses that have helped 14,000+ tech professionals
blue tick
100% money-back guarantee*
Register for Webinar
All Blog Posts