Video summary
Sort Colors - Quicksort Partition - Leetcode 75 - Python
Main summary
Key takeaways
Main ideas / lessons
-
“Sort Colors” problem: Given an array
numscontaining only{0, 1, 2}, sort it in ascending order so that:- all
0s come first, - then all
1s, - then all
2s.
- all
-
The speaker emphasizes efficiency and why generic sorting is overkill:
- Standard library/general sorting is typically
O(n log n). - Since there are only three distinct values, more specialized solutions exist.
- Standard library/general sorting is typically
-
Two core approaches are discussed:
Methodology / instructions (detailed steps)
Approach 1: Bucket/counting (linear time)
Idea: Count how many of each value appear, then overwrite the array in-place.
-
Create counters for the three values:
count0,count1,count2(conceptually three “buckets” or a tiny map/array)
-
First scan:
- For each element in
nums, increment the corresponding counter.
- For each element in
-
Second phase: overwrite in-place:
- Write
count0zeros at the beginning. - Write
count1ones immediately after the zeros. - Write
count2twos at the end.
- Write
Complexity (as claimed):
- Time:
O(n) - Extra space:
O(1)(only three counters)
Approach 2: One-pass partition (Dutch National Flag–style)
Goal: Partition the array in one scan into three regions:
- Left region: all
0s - Middle region: all
1s - Right region: all
2s
Pointers
left= start index (initially0)right= end index (initiallylen(nums) - 1)i= scanning index (runs whilei <= right)
Loop condition
- While
i <= right, processnums[i].
In-place swap logic
- Use a helper swap that swaps values directly inside the array, e.g. swapping
nums[i]andnums[j].
Case handling for nums[i]
-
If
nums[i] == 0:- Swap
nums[i]withnums[left] - Increment
leftby 1 - Allow
ito increment normally via the loop - Rationale:
lefttracks a region where values should ultimately be1/unprocessed, so inserting a0there is safe.
- Swap
-
If
nums[i] == 2:- Swap
nums[i]withnums[right] - Decrement
rightby 1 - Do not advance
iimmediately after the swap - Rationale (edge case):
- Swapping with
rightmay bring a new, unprocessed value into positioni. - If the incoming value is
0, it must be handled—soimust be re-checked.
- Swapping with
- Swap
-
If
nums[i] == 1:- Do nothing besides letting the loop move on (
iincrements normally) - Rationale: ones belong in the middle region.
- Do nothing besides letting the loop move on (
Termination
- Stop when
isurpassesright.
At that point:
- everything left of
leftis0, - everything right of
rightis2, - the remaining middle section is
1s.
Example result: 0,0,1,1,2,2
Speakers / sources featured
- Speaker: “hey everyone welcome back…” (unnamed presenter/channel host)
- Referenced concepts/algorithms:
- quicksort’s partition concept
- bucket sort/counting concept
- LeetCode problem: “Sort Colors” / “Leetcode 75”