3Sum Problem
Budget Shopping & Zero Balance Checkout

π§© What's the Problem?
You're at your favorite online store. You've added a bunch of items to your cart, applied a couple of gift cards and discount coupons β but you want to balance your checkout perfectly. That means:
Pick any three things β products, gift cards, or coupons β whose total value adds up to zero.
Some items cost you money (+ve), others give you money back like cashback or gift cards (-ve), and some are free (0).
So your goal is:
π― Find all unique combinations of 3 items where the total cost is zero.
π§ͺ Example
Input: nums = [-1, 0, 1, 2, -1, -4]
Output: [[-1, -1, 2], [-1, 0, 1]]
- One combo: -1 (discount) + -1 (gift card) + 2 (expensive item) = 0
- Another combo: -1 + 0 + 1 = 0
- Triplets like [0, 1, -1] are considered duplicates of [β1, 0, 1], so we donβt count them twice.
π οΈ How Do We Solve It?
Letβs say you have a cart with n items. Checking all combinations of 3 manually would take O(nΒ³) time (slow). We want a smarter way β and thatβs where sorting and two pointers come in.
Think of it like this:
π Step-by-Step Shopping Strategy:
1. Sort the cart items.
- That way, your costs and discounts are in order β like neatly arranging your cart.
2. Fix the first item (letβs call it i) β like picking the first thing youβre sure you want.
3. Now, you need two more items that will cancel out the cost of the first one.
- So the new target becomes: 0 - nums[i].
4. Use a two-pointer approach to find this pair:
- left starts just after i
- right starts at the end
5. Move the pointers smartly:
- If the sum is too low β move left up
- If itβs too high β move right down
- If itβs just right β bingo! Add the triplet
6. Skip duplicates so we donβt end up with repeated combos.
π¦ The Code (Java)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums); // Step 1: Sort your cart
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue; // Skip duplicates
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
// Skip duplicates
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) {
left++; // Need a bigger number
} else {
right--; // Need a smaller number
}
}
}
return result;
}
}
Walkthrough Example β Letβs Shop!
Input:
nums = [-1, 0, 1, 2, -1, -4]
Step 1: π§Ή Sort the prices
Sorting helps organize our search and avoid duplicate bundles.
Sorted: [-4, -1, -1, 0, 1, 2]
Step 2: Try each item as the first pick
We fix one item at a time (index i) and use two pointers (left and right) to find two other items such that their total is zero.
π· i = 0 β nums[i] = -4
- left = 1 (nums[left] = -1), right = 5 (nums[right] = 2)
- Total = -4 + (-1) + 2 = -3 β too low
β‘οΈ Move left β left = 2 (nums[left] = -1)
- Total = -4 + (-1) + 2 = -3 β still too low
β‘οΈ Move left β left = 3 β left >= right β Stop
π No valid bundle with -4
π· i = 1 β nums[i] = -1
- left = 2 (nums[left] = -1), right = 5 (nums[right] = 2)
- Total = -1 + (-1) + 2 = 0 β
π Found triplet: [-1, -1, 2]
β‘οΈ Move left to 3, right to 4
- New Total = -1 + 0 + 1 = 0 β
π Found triplet: [-1, 0, 1]
β‘οΈ Move left to 4, right to 3 β Stop
π·i = 2 β nums[i] = -1 again β β skip duplicate
π· i = 3 β nums[i] = 0
- left = 4 (1), right = 5 (2)
- Total = 0 + 1 + 2 = 3 β too high
β‘οΈ Move right to 4 β left >= right β Stop
π No valid bundle with 0
β Final Answer:
[[-1, -1, 2], [-1, 0, 1]]
π Time and Space Complexity
1. Time Complexity:
- Sorting the array takes O(n log n).
- For each element, we perform a two-pointer search in O(n) time.
- The overall time complexity is O(nΒ²).
2. Space Complexity:
- We are using extra space to store the result (which can contain up to O(n) triplets).
- Therefore, the space complexity is O(n).
π Key Takeaways:
1. Sort first, then search:
Sorting the array helps organize the search and avoid duplicates.
2. The two-pointer trick:
Use the two-pointer approach after fixing one element. It makes finding the right pair much more efficient.
3. Skip duplicates:
After finding a valid triplet, skip the same combinations to keep your results unique.
4. Efficiency over brute force:
This approach reduces the problem's time complexity from O(nΒ³) to O(nΒ²), making it much more efficient.
About the Creator
Sreya Satheesh
Senior Software Engineer | Student
https://github.com/sreya-satheesh
https://leetcode.com/u/sreya_satheesh/
Enjoyed the story? Support the Creator.
Subscribe for free to receive all their stories in your feed.
Comments