NeetCode #93LC-75MediumArrays & HashingNC 250
← Back to All Problems#93 · #75 · Sort Colors(颜色分类)
📌 Problem Statement & Constraints
Given an array
nums with n objects coloured red (0), white (1) or blue (2), sort them in place so that objects of the same colour are adjacent, in the order red, white, blue. You must solve it without using the library sort function, ideally in a single pass. Constraints: 1 <= n <= 300, nums[i] is 0, 1 or 2.💡 Core Algorithmic Approaches
- Dutch national flag algorithm (Dijkstra): three pointers partition the array into four regions.
- Invariant:
[0, low)is all 0s,[low, mid)is all 1s,(high, n-1]is all 2s, and[mid, high]is unexamined. - Inspect
nums[mid]: if it is 0, swap it into the 0-region (nums[low], nums[mid] = nums[mid], nums[low]) and advance bothlowandmid. If it is 1, just advancemid. If it is 2, swap it into the 2-region and decrementhighwithout advancingmid-- the swapped-in element is unexamined. - The loop runs while
mid <= high, and each element is inspected once, giving a genuine single pass.
💻 Benchmark Python3 Implementation
class Solution:
def sortColors(self, nums: List[int]) -> None:
low, mid, high = 0, 0, len(nums) - 1
while mid <= high:
if nums[mid] == 0:
nums[low], nums[mid] = nums[mid], nums[low]
low += 1
mid += 1
elif nums[mid] == 1:
mid += 1
else: # nums[mid] == 2
nums[mid], nums[high] = nums[high], nums[mid]
high -= 1 # do NOT advance mid: new element unseen
# regions: [0,low) = 0s, [low,mid) = 1s, (high,n-1] = 2s
# Counting sort: two passes, simpler to get right
class Solution2:
def sortColors(self, nums: List[int]) -> None:
cnt = [0, 0, 0]
for x in nums:
cnt[x] += 1
i = 0
for v in range(3):
for _ in range(cnt[v]):
nums[i] = v
i += 1⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n) for both variants. The Dutch flag version makes exactly one pass; counting sort makes two.
💾 Space Complexity
O(1) for both -- only a handful of integer variables, versus a 3-element counter array.
⚠️ Interview Pitfalls & Follow-ups
- Advancing
midafter swapping a 2 to the back: the element swapped in fromhighhas never been inspected, somidmust stay put. This is the single most common bug. - Using
while mid < high: the last unexamined element is skipped. Use<=. - Swapping 0 to the front and incrementing only
low:midmust also advance, because the element atmidafter the swap is known to be a 1 (it came from the 1-region). - Writing a generic two-pass partition or a full quick sort: it works, but the point of the exercise is the three-way partition in one pass.
- Returning the array: the signature returns
None; the sort must happen in place.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
颜色分类
给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。我们使用整数 0、1 和 2 分别表示红色、白色和蓝色。必须在不使用库内置的 sort 函数的情况下解决这个问题。进阶:你能想出一个仅使用常数空间的一趟扫描算法吗?约束:n == nums.length;1 ≤ n ≤ 300;nums[i] 为 0、1 或 2。
核心要点
- 计数排序(两趟) :第一趟统计 0/1/2 各有多少个,第二趟按计数回填。时间 O(n)、空间 O(1),但不满足「一趟扫描」的进阶要求。
- 荷兰国旗问题 · 三指针一趟扫描(最优) :维护三个指针——low 指向 0 区的右边界、mid 为当前扫描位置、high 指向 2 区的左边界。
- 循环不变量 : [0, low) 全是 0, [low, mid) 全是 1, (high, n-1] 全是 2, [mid, high] 是待处理区。
- 三种情况的处理 :nums[mid] == 0 时交换 nums[low] 与 nums[mid],low 与 mid 同时右移;== 1 时只 mid 右移;== 2 时交换 nums[mid] 与 nums[high],只 high 左移( mid 不右移 ,因为换过来的元素尚未检查)。
常见陷阱
- 交换 2 之后把 mid 也右移 :这是本题最经典的 bug。从 high 换过来的元素尚未检查,mid 必须停在原地重新判断,否则会漏排。
- 循环条件写成 mid < high :必须是 mid <= high ,因为 mid == high 时该位置仍需检查。写成严格小于会漏掉最后一个元素。
- 用「排序后统计」的思路答进阶问题 :计数排序是两趟扫描,不满足「一趟」要求。面试官问进阶时就是要荷兰国旗算法。
- 被追问 扩展到 k 种颜色 时答不上来:三指针法只适用于 3 种值。k 种颜色需用计数排序(两趟 O(n + k)),或对 k 很小时嵌套划分。
参考实现
class Solution:
def sortColors(self, nums: list[int]) -> None:
"""原地排序,一趟扫描,O(1) 额外空间。"""
low, mid, high = 0, 0, len(nums) - 1
while mid <= high:
if nums[mid] == 0:
nums[low], nums[mid] = nums[mid], nums[low]
low += 1
mid += 1
elif nums[mid] == 1:
mid += 1
else: # nums[mid] == 2
nums[mid], nums[high] = nums[high], nums[mid]
high -= 1 # mid 不动:换过来的元素还没检查