3Sum in Python and Java
In this tutorial, we will learn LeetCode #15: 3Sum in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.
What Is the 3Sum Problem?
This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.
For this problem, we will use sorting and two pointers because it gives a clean and optimized solution.
Example input: nums = [-4, -1, -1, 0, 1, 2, 5] Expected result: Output: [[-1, -1, 2], [-1, 0, 1]] Explanation: These triplets add to zero.
Beginner-Friendly Idea
The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.
At each step, ask: “What do I already know, and how does the current value change my answer?”
Using our example: nums = [-4, -1, -1, 0, 1, 2, 5] Approach: sorting and two pointers We update variables step by step until we reach: Output: [[-1, -1, 2], [-1, 0, 1]]
Why Do We Use This Approach?
A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.
That is why sorting and two pointers is useful for this problem.
Step-by-Step Explanation
Let us dry run the algorithm using a custom example.
Step 1 Use this custom example. nums = [-4, -1, -1, 0, 1, 2, 5] We will solve it using sorting and two pointers. Step 2 Look at the first important value from the example and create the variables needed by the algorithm. current_state = based on the first value answer = not finished yet Step 3 Move to the next useful value and update the state. The algorithm compares the new value with the old state. If the new value improves the answer, we update the answer. Step 4 Continue this process until all useful values are processed. After processing the example, we get: Output: [[-1, -1, 2], [-1, 0, 1]] Why? These triplets add to zero.
Important Code Logic
The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.
Think like this: old_state = what we knew before current_value = value we are checking now new_state = updated result after using current_value For our example, the final state gives: Output: [[-1, -1, 2], [-1, 0, 1]]
Example 1
Input: nums = [-4, -1, -1, 0, 1, 2, 5] Output: Output: [[-1, -1, 2], [-1, 0, 1]] Explanation: These triplets add to zero.
Example 2
Input: nums = [-5, -2, -1, 0, 1, 2, 4] Output: [[-2, 0, 2], [-1, 0, 1]] Explanation: These two triplets add up to zero.
Python Code
Here is the complete Python solution for LeetCode #15.
class ThreeSumFinder:
def three_sum(self, nums):
nums.sort()
result = []
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
left = i + 1
right = len(nums) - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total == 0:
result.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif total < 0:
left += 1
else:
right -= 1
return result
finder = ThreeSumFinder()
print(finder.three_sum([-4, -1, -1, 0, 1, 2, 5]))
print(finder.three_sum([-2, 0, 1, 1, 2]))Java Code
Here is the complete Java solution for LeetCode #15.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class ThreeSumFinder {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int total = nums[i] + nums[left] + nums[right];
if (total == 0) {
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
left++;
right--;
while (left < right && nums[left] == nums[left - 1]) left++;
while (left < right && nums[right] == nums[right + 1]) right--;
} else if (total < 0) {
left++;
} else {
right--;
}
}
}
return result;
}
public static void main(String[] args) {
ThreeSumFinder finder = new ThreeSumFinder();
System.out.println(finder.threeSum(new int[] {-4, -1, -1, 0, 1, 2, 5}));
System.out.println(finder.threeSum(new int[] {-2, 0, 1, 1, 2}));
}
}Time and Space Complexity
Time Complexity: O(n log n)
The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.
Space Complexity: O(n)
The extra space is used for the variables or data structures needed by the optimized approach.
Final Summary
LeetCode #15: 3Sum becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.