top of page

Looking to master object-oriented and system design for tech interviews or career growth?

  • Improve your system design and machine coding skills.

  • Study with our helpful resources.

  • Prepare for technical interviews and advance your career.

**We're in beta mode and would love to hear your feedback.

3 Sum Zero - InterviewBit Solution

Feb 1, 2022
1 min read

Problem: 3 Sum Zero


Problem Description:

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?

Find all unique triplets in the array which gives the sum of zero.


Note:

Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)

The solution set must not contain duplicate triplets.

For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)

Solution Approach:




Solution:

Code in C++

If you have any questions or queries, feel free to drop a comment in the comments section below.


Note: Help us improve this blog

If you have a better solution, and you think you can help your peers to understand this problem better, then please drop your solution and approach in the comments section below.

We will upload your approach and solution here by giving you the proper credit so that you can showcase it among your peers.

2 Comments


https://paysafecardcasinolist.com came to mind while reading your approach, since sorting first and then fixing one pointer while moving the other is the same kind of step-by-step logic that keeps things manageable when the input gets messy. The detail about skipping duplicates at all three positions is what stuck with me, because that's usually where I mess up and end up with repeated triplets in the output. Curious whether you'd handle the no-solution case with an early break or just let the loop finish naturally.

Like

vector<vector<int>> Solution::threeSum(vector<int> &A) {

sort(A.begin(), A.end());

vector<vector<int>> res;

for (int i = 0; i < A.size(); i++) {

if (i > 0 && A[i] == A[i - 1]) continue;

int l = i + 1, r = A.size() - 1;

while (l < r) {

int sum = A[i] + A[l] + A[r];

if (sum == 0) {

res.push_back({A[i], A[l], A[r]});

while (l < r && A[l] == A[l + 1]) l++;

while (l < r && A[r] == A[r - 1]) r--;

l++; r--;

}

else if (sum < 0) l++;

else r--;

}

}

return res;

}

short programming 3 sum zero coding


Like
bottom of page