Sort Colors (Dutch National Flag)
Three-Way Partitioning / Two PointersSolved Nov 17, 2025
Asked at 12 companies
9 recent
- Walmart Labs
- Agoda
- Microsoft
- tcs
- Amazon
- Bloomberg
- Meta
- Infosys
- Pocket Gems
+2 moreShow fewer
- Slice
- Target
Community-reported · source · updated 2026-10-08. ● asked in the last 6 months.
Go step by step: try it yourself before the video and the visual. Progress saves on this device.
0 / 130 pointsSolved (Medium) 0/40Reviews 0/50Mastered 0/25Practice steps 0/15
Step 1
Know these before you start
Practise each one here, or tick what you already know
Step 2
Try it on paper
5–10 minutes, no code yet
In the wild · Every “Sort by” button: Sorting a spreadsheet by price, then by name, needs a stable sort, which is why Python and JavaScript both use merge-sort-based TimSort.
ProblemProblem statementGiven an array nums with n objects colored red, white, or blue (represented by the integers 0, 1, and 2, respectively), sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.ReadHide
Problem Description
Given an array nums with n objects colored red, white, or blue (represented by the integers 0, 1, and 2, respectively), sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
Code it here
Tab indents · ⌘/Ctrl+Enter runs · Esc leaves the editor
Step 6
Get it accepted
All test cases pass
Step 7
Review it so it sticks
Re-solve from memory after
The step that matters most: without reviews most of a solved problem fades within weeks. Three short re-solves, each just as you start to forget, are what make it yours.
Your notes
Three lines in your own words. They come back with this problem's reviews, so you can check yourself after recalling the solution.
Solve it yourself before you look
Reading the solution first feels like progress, but it makes the next similar problem — and the interview version — much harder, because you skipped the part where you figure it out. Give it an honest 20–30 minutes. Stuck? Re-read the pattern, watch the concept video, or try the brute force first.
Hidden: approach · solution code · optimal solution
Approach
Use three pointers (low, mid, high) to maintain three regions: [0, low-1] are 0s, [low, mid-1] are 1s, and [high+1, N-1] are 2s. Process elements at 'mid' in a single pass.
Approaches
1. Dutch National Flag Algorithm (Optimal) - O(N) ⭐
Idea: This specialized algorithm sorts elements into three partitions in a single pass, achieving linear time complexity, which is faster than any comparison-based sort (O(N log N)).
- Initialize three pointers:
low = 0,mid = 0,high = N-1. - Iterate while
mid <= high.- If
nums[mid] == 0: Swapnums[mid]withnums[low]. Incrementlowandmid. - If
nums[mid] == 1: Incrementmid. - If
nums[mid] == 2: Swapnums[mid]withnums[high]. Decrementhigh. (Do not incrementmidbecause the swapped element atmidneeds to be checked).
- If
2. Brute Force (Comparison Sort) - O(N log N)
Idea: Simply use a standard general-purpose sorting algorithm (like Quick Sort or Merge Sort). This is unnecessary overkill since the input domain is limited to only three values.
Solution code
from typing import List
class Solution:
# Optimized: O(N) Time, O(1) Space - Dutch National Flag Algorithm
def sortColors_optimal(self, nums: List[int]):
low = 0 # Pointer for the 0s region
mid = 0 # Current element pointer (the one being checked)
high = len(nums) - 1 # Pointer for the 2s region
while mid <= high:
if nums[mid] == 0:
# Swap current 0 to the low region
nums[low], nums[mid] = nums[mid], nums[low]
low += 1
mid += 1
elif nums[mid] == 1:
# 1 is already in the middle region, just move on
mid += 1
else: # nums[mid] == 2
# Swap current 2 to the high region (do NOT increment mid)
nums[high], nums[mid] = nums[mid], nums[high]
high -= 1
# This function modifies nums in-place
# Brute Force: O(N log N) Time - Any general-purpose sort
def sortColors_brute(self, nums: List[int]):
# Using Python's built-in sort (TimSort, O(N log N)) for the brute force comparison
nums.sort()Other ways to solve it
- Thought of another approach (slower, or cleverer)? Code it here: the same tests check any approach.
- Community solutions on LeetCode ↗ for many more versions, in many languages. Read them after you've solved it.
Revising this one?
- →Solve it from memory before peeking
- →Say the pattern out loud, not just the code
- →Explain it like you would to a friend
- →Try it again in a different language