Data Structures & Algorithms Sorting Algorithms
💡
Exercise 59

Sort Colors 20 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Given an array with n objects colored red (0), white (1), and blue (2), sort them in-place so same colors are adjacent, in order: red, white, blue.

This is the famous Dutch National Flag problem by Dijkstra.

nums = [2,0,2,1,1,0] → [0,0,1,1,2,2]

Use three pointers: low (boundary for 0s), mid (current), high (boundary for 2s). One pass, O(n) time, O(1) space!

  • If nums[mid] == 0: swap with low, move both forward
  • If nums[mid] == 1: just move mid forward
  • If nums[mid] == 2: swap with high, move high back (don't move mid — the swapped value needs checking)
📋 Instructions
Implement `sort_colors(nums)` using the Dutch National Flag algorithm. Sort `[2,0,2,1,1,0]` in-place and print the result.
Three pointers: low=0, mid=0, high=len-1. While mid <= high, check nums[mid] and swap/move accordingly.
🧪 Test Cases
Input
sort_colors([2,0,2,1,1,0])
Expected
[0, 0, 1, 1, 2, 2]
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.