Algorithm Day99 - Sort Colors
π§© Problem
LeetCode 75 - Sort Colors
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the colors red, white, and blue respectively.
You must solve this problem without using the libraryβs sort function.
Example:
1 | Input: nums = [2,0,2,1,1,0] |
π‘ Idea
This is a Dutch National Flag problem, invented by Edsger Dijkstra.
We use three pointers to partition the array into three regions:
0 ... low-1: all 0slow ... mid-1: all 1shigh+1 ... end: all 2s
We iterate using mid:
- If
nums[mid] == 0: swap withlow, increment bothlowandmid - If
nums[mid] == 1: just incrementmid - If
nums[mid] == 2: swap withhigh, decrementhigh
This ensures a one-pass, in-place sorting solution.
π» Java Code
1 | class Solution { |
π§ Complexity
- Time: O(n) β Single pass through the array
- Space: O(1) β In-place swaps only
π Summary
This problem is a perfect example of in-place array manipulation using multiple pointers.
The Dutch National Flag algorithm is elegant, efficient, and a must-know for array partitioning problems.