Three Sum Problem All Unique Triplets in DSA Python - Time & Space Complexity
We want to understand how the time needed grows when finding all unique triplets that sum to zero in a list.
How does the number of steps change as the list gets bigger?
Analyze the time complexity of the following code snippet.
nums.sort()
result = []
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i-1]:
continue
left, right = i + 1, len(nums) - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total < 0:
left += 1
elif total > 0:
right -= 1
else:
result.append([nums[i], nums[left], nums[right]])
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
left += 1
right -= 1
This code finds all unique triplets in the list that add up to zero using sorting and two pointers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The outer loop runs through each element once, and inside it, a while loop moves two pointers through the remaining elements.
- How many times: The outer loop runs n times, and the inner while loop moves pointers across the list, together covering the list roughly n times for each outer loop.
As the list size grows, the number of steps grows much faster because for each element, we scan the rest with two pointers.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 100 steps |
| 100 | About 10,000 steps |
| 1000 | About 1,000,000 steps |
Pattern observation: The steps grow roughly with the square of the input size, meaning if the list size doubles, the work increases about four times.
Time Complexity: O(n²)
This means the time needed grows roughly with the square of the list size, so doubling the list makes the work about four times bigger.
[X] Wrong: "The time complexity is O(n³) because there are three nested loops."
[OK] Correct: The code uses sorting and two pointers inside a single loop, not three nested loops. The inner while loop moves pointers forward without restarting, so total work is less than cubic.
Understanding this problem's time complexity helps you explain how to handle searching pairs efficiently after sorting, a skill useful in many coding challenges.
"What if we used three nested loops instead of two pointers? How would the time complexity change?"
Practice
Three Sum Problem in arrays?Solution
Step 1: Understand the problem statement
The Three Sum Problem asks to find all unique sets of three numbers in an array that add up to zero.Step 2: Differentiate from other sum problems
Unlike finding pairs or maximum sums, this problem focuses on triplets with sum exactly zero and uniqueness.Final Answer:
Find all unique triplets that sum to zero -> Option AQuick Check:
Three Sum = unique triplets summing to zero [OK]
- Confusing with pair sum problems
- Looking for maximum sum instead of zero sum
- Ignoring uniqueness of triplets
Solution
Step 1: Identify the correct data structure for storing triplets
Triplets are stored as lists inside a list, so initializing an empty list is correct.Step 2: Analyze other options
{} creates a dictionary, set() is for unique single elements, None is not a container.Final Answer:
triplets = [] -> Option AQuick Check:
Empty list for triplets = [] [OK]
- Using {} which creates a dictionary
- Using set() which stores unique single elements, not lists
- Assigning None which is not a container
nums = [-1, 0, 1, 2, -1, -4]?
def three_sum(nums):
nums.sort()
result = []
for i in range(len(nums)-2):
if i > 0 and nums[i] == nums[i-1]:
continue
left, right = i+1, len(nums)-1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total == 0:
result.append([nums[i], nums[left], nums[right]])
while left < right and nums[left] == nums[left+1]:
left += 1
while left < right and nums[right] == nums[right-1]:
right -= 1
left += 1
right -= 1
elif total < 0:
left += 1
else:
right -= 1
return result
print(three_sum(nums))Solution
Step 1: Sort the input array
Sorted nums = [-4, -1, -1, 0, 1, 2]Step 2: Find unique triplets summing to zero
Triplets found are [-1, -1, 2] and [-1, 0, 1]. These are appended to result.Final Answer:
[[-1, -1, 2], [-1, 0, 1]] -> Option DQuick Check:
Triplets sum zero = [[-1,-1,2],[-1,0,1]] [OK]
- Not sorting the array before processing
- Including duplicate triplets
- Incorrect pointer movement causing missed triplets
def three_sum(nums):
nums.sort()
result = []
for i in range(len(nums)):
left, right = i+1, 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
elif total < 0:
left += 1
else:
right -= 1
return result
print(three_sum([-1, 0, 1, 2, -1, -4]))Solution
Step 1: Check for duplicate skipping logic
The code lacks 'if i > 0 and nums[i] == nums[i-1]: continue' and inner while loops to skip duplicate left/right values after finding a triplet. This causes duplicate triplets like [-1, 0, 1] appearing twice.Step 2: Verify other parts
Sorting is present, pointers initialized correctly, loop range to len(nums) is unnecessary but does not cause errors or duplicates.Final Answer:
No check to skip duplicate triplets -> Option BQuick Check:
Missing duplicate skips cause repeated triplets [OK]
- Missing 'if i > 0 and nums[i] == nums[i-1]' check
- No inner while loops to skip duplicate left/right
- Thinking loop range causes index errors (it doesn't)
nums = [0, 0, 0, 0], what is the correct output of a Three Sum solution that returns all unique triplets summing to zero?Solution
Step 1: Understand uniqueness requirement
Even though multiple zeros exist, only one unique triplet [0, 0, 0] should be returned.Step 2: Check triplet formation
Triplet [0, 0, 0] sums to zero and is valid. Duplicates must be avoided.Final Answer:
[[0, 0, 0]] -> Option CQuick Check:
Unique triplets = [[0,0,0]] [OK]
- Returning duplicate triplets multiple times
- Returning pairs instead of triplets
- Returning empty list when triplets exist
Ready to prove it?
Pass the test and this pattern moves unknown
