Data Structures & Algorithms Two Pointers
💡
Exercise 37

3Sum 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Given an array nums, return all unique triplets [nums[i], nums[j], nums[k]] such that i != j != k and nums[i] + nums[j] + nums[k] == 0.

The solution must not contain duplicate triplets.

nums = [-1, 0, 1, 2, -1, -4] # Output: [[-1, -1, 2], [-1, 0, 1]]

Strategy: Sort the array, then for each number, use Two Sum II (two pointers) on the remaining elements. Skip duplicates to avoid repeats.

📋 Instructions
Implement `three_sum(nums)` that returns all unique triplets summing to 0. Test with `nums = [-1, 0, 1, 2, -1, -4]`. Print the sorted result.
Sort the array first! Then use two pointers inside a loop. Skip duplicates to avoid repeated triplets. For each number, find two others that sum to its negative.
🧪 Test Cases
Input
three_sum([-1, 0, 1, 2, -1, -4])
Expected
[[-1, -1, 2], [-1, 0, 1]]
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.