1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Find all unique triplets in the list that add up to zero.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1If you fix the first number, what must the other two add up to?
- Hint 2How do you avoid reporting the same triplet twice?
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
Three friends settle a trip bill so that what some owe and what others are owed cancels exactly to zero. Line everyone up from most-owing to most-owed. Fix the first friend; now the other two must together cancel him, which is the same "two people from a sorted line" job as Two Sum II. To avoid listing the same trio twice, never pick the same amount twice in the same role.
- The obvious way
Three nested loops with a set of results: O(n³).
- The key insight
Sort. For each first number (skipping repeats) search the numbers to its right for a pair that cancels it, using the two-pointer sweep from Two Sum II. After a hit, move both pointers inward and skip equal values so each triplet is reported once. O(n²) overall.
- The algorithm
- Sort the numbers.
- Pick a first number. Same as the previous first number? Skip it.
- Put one pointer just after it, one at the end. Add the three. Too small: left pointer right. Too big: right pointer left.
- Zero? Record the triplet and move on, skipping equal values.
Watch it run
Examplenumbers (sorted) = [-4, -1, -1, 0, 1, 2]
First = -4. The best remaining pair is 1 + 2 = 3, never reaching 4. No triplet.
found: none
Where people slip
- Skip duplicates for the first number and, after a hit, for the second. The third then takes care of itself.
- Quick exit: once the first number is above zero, three positives can never sum to zero.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def three_sum(nums):
nums.sort()
triplets = []
for first in range(len(nums) - 2):
if first > 0 and nums[first] == nums[first - 1]:
continue # same first number as before
left, right = first + 1, len(nums) - 1
while left < right:
total = nums[first] + nums[left] + nums[right]
if total < 0:
left += 1
elif total > 0:
right -= 1
else:
triplets.append([nums[first], nums[left], nums[right]])
left += 1
while left < right and nums[left] == nums[left - 1]:
left += 1 # skip equal second numbers
return tripletsNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.