0
0
DSA Pythonprogramming~10 mins

Three Sum Problem All Unique Triplets in DSA Python - Execution Trace

Choose your learning style9 modes available
Concept Flow - Three Sum Problem All Unique Triplets
Sort the array
Fix first element i
Set left = i+1, right = end
Calculate sum = nums[i
Add triplet
Move left and right skipping duplicates
Move left right to increase sum
Move right left to decrease sum
Repeat until left >= right
Move i to next unique element
Repeat until i reaches end
Return all unique triplets
We sort the array, then fix one element and use two pointers to find pairs that sum to zero with it, skipping duplicates to get unique triplets.
Execution Sample
DSA Python
nums = [-1, 0, 1, 2, -1, -4]
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:
    s = nums[i] + nums[left] + nums[right]
    if s == 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 s < 0:
      left += 1
    else:
      right -= 1
This code sorts the array and uses a fixed pointer with two moving pointers to find triplets summing to zero.
Execution Table
StepOperationileftrightSumTriplets FoundPointer ChangesArray State
1Sort array----[]-[-4, -1, -1, 0, 1, 2]
2Fix i at 0015-[]Set left=1, right=5[-4, -1, -1, 0, 1, 2]
3Calculate sum015-4 + (-1) + 2 = -3[]sum < 0, move left right[-4, -1, -1, 0, 1, 2]
4Move left025-[]left=2[-4, -1, -1, 0, 1, 2]
5Calculate sum025-4 + (-1) + 2 = -3[]sum < 0, move left right[-4, -1, -1, 0, 1, 2]
6Move left035-[]left=3[-4, -1, -1, 0, 1, 2]
7Calculate sum035-4 + 0 + 2 = -2[]sum < 0, move left right[-4, -1, -1, 0, 1, 2]
8Move left045-[]left=4[-4, -1, -1, 0, 1, 2]
9Calculate sum045-4 + 1 + 2 = -1[]sum < 0, move left right[-4, -1, -1, 0, 1, 2]
10Move left055-[]left=5[-4, -1, -1, 0, 1, 2]
11left >= right055-[]End inner loop[-4, -1, -1, 0, 1, 2]
12Move i to 1125-[]Skip duplicates for i[-4, -1, -1, 0, 1, 2]
13Calculate sum125-1 + (-1) + 2 = 0[[-1, -1, 2]]sum == 0, add triplet, move left and right skipping duplicates[-4, -1, -1, 0, 1, 2]
14Move left134-[[-1, -1, 2]]left=3[-4, -1, -1, 0, 1, 2]
15Move right134-[[-1, -1, 2]]right=4[-4, -1, -1, 0, 1, 2]
16Calculate sum134-1 + 0 + 1 = 0[[-1, -1, 2], [-1, 0, 1]]sum == 0, add triplet, move left and right skipping duplicates[-4, -1, -1, 0, 1, 2]
17Move left143-[[-1, -1, 2], [-1, 0, 1]]left=4[-4, -1, -1, 0, 1, 2]
18left >= right143-[[-1, -1, 2], [-1, 0, 1]]End inner loop[-4, -1, -1, 0, 1, 2]
19Move i to 22---[[-1, -1, 2], [-1, 0, 1]]Skip duplicate i=2 because nums[2] == nums[1][-4, -1, -1, 0, 1, 2]
20Move i to 3345-[[-1, -1, 2], [-1, 0, 1]]Set left=4, right=5[-4, -1, -1, 0, 1, 2]
21Calculate sum3450 + 1 + 2 = 3[[-1, -1, 2], [-1, 0, 1]]sum > 0, move right left[-4, -1, -1, 0, 1, 2]
22Move right344-[[-1, -1, 2], [-1, 0, 1]]right=4[-4, -1, -1, 0, 1, 2]
23left >= right344-[[-1, -1, 2], [-1, 0, 1]]End inner loop[-4, -1, -1, 0, 1, 2]
24Move i to 44---[[-1, -1, 2], [-1, 0, 1]]i reaches len(nums)-2, end loop[-4, -1, -1, 0, 1, 2]
💡 i reaches len(nums)-2, no more triplets possible
Variable Tracker
VariableStartAfter Step 2After Step 12After Step 20Final
i-0134
left-1244
right-5554
Triplets Found[][][[-1, -1, 2]][[-1, -1, 2], [-1, 0, 1]][[-1, -1, 2], [-1, 0, 1]]
Array State[-1, 0, 1, 2, -1, -4][-4, -1, -1, 0, 1, 2][-4, -1, -1, 0, 1, 2][-4, -1, -1, 0, 1, 2][-4, -1, -1, 0, 1, 2]
Key Moments - 3 Insights
Why do we skip duplicate values for i and left/right pointers?
Skipping duplicates prevents adding the same triplet multiple times. For example, at step 19, i=2 is skipped because nums[2] == nums[1], avoiding repeated triplets as shown in execution_table rows 13-18.
Why do we move left pointer when sum < 0 and right pointer when sum > 0?
Because the array is sorted, moving left pointer right increases sum, and moving right pointer left decreases sum. This is shown in steps 3-10 and 21-22 in the execution_table.
Why does the inner loop stop when left >= right?
When left meets or passes right, all pairs for the fixed i are checked. This is shown at steps 11, 18, 23 where the inner loop ends.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 13, what triplet is added to the result?
A[-1, -1, 2]
B[-1, 0, 1]
C[-4, 1, 2]
D[0, 1, 2]
💡 Hint
Check the 'Triplets Found' column at step 13 in execution_table
At which step does the sum first equal zero?
AStep 3
BStep 13
CStep 16
DStep 21
💡 Hint
Look at the 'Sum' column in execution_table and find the first zero value
If we did not skip duplicates for i, what would happen in the execution?
AMore unique triplets would be found
BThe algorithm would run faster
CDuplicate triplets would be added multiple times
DNo triplets would be found
💡 Hint
Refer to key_moments about skipping duplicates and step 19 in execution_table
Concept Snapshot
Three Sum Problem:
- Sort the array first
- Fix one element i
- Use two pointers left=i+1 and right=end
- Calculate sum = nums[i]+nums[left]+nums[right]
- If sum==0, add triplet and skip duplicates
- If sum<0, move left right to increase sum
- If sum>0, move right left to decrease sum
- Repeat until all unique triplets found
Full Transcript
The Three Sum problem finds all unique triplets in an array that sum to zero. We start by sorting the array to use the two-pointer technique efficiently. We fix one element at a time and set two pointers: one just after the fixed element and one at the end of the array. We calculate the sum of these three elements. If the sum is zero, we add the triplet to the result and move both pointers skipping duplicates to avoid repeated triplets. If the sum is less than zero, we move the left pointer right to increase the sum. If the sum is greater than zero, we move the right pointer left to decrease the sum. We repeat this process until the pointers meet. Then we move the fixed element to the next unique value and repeat. This approach ensures all unique triplets are found efficiently.