π Introduction
Given an array nums with n objects colored red (0), white (1), or blue (2), sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
*Constraints typically include:
- You must solve this problem without using the libraryβs sort function.
- The array contains only values 0, 1, and 2.*
π‘ Approach & Key Insights
The problem can be solved through various approaches. Though sorting is a valid but not expected solution, we can explore better and optimal methods by leveraging the limited number of distinct values (0, 1, 2). This allows for more efficient counting or pointer-based techniques like the Dutch National Flag algorithm.
π οΈ Breakdown of Approaches
1οΈβ£ Brute Force / Naive Approach
- Explanation: Use the built-in sorting algorithm to sort the array. This works since the array contains only 0, 1, and 2, and sorting would naturally arrange them.
- Time Complexity:Β O(n log n) β standard sorting complexity.
- Space Complexity:Β O(1) β assuming in-place sort.
- Example/Dry Run:
Input: [2, 0, 2, 1, 1, 0]Sorted Output: [0, 0, 1, 1, 2, 2]
2οΈβ£ Better Approach
- Explanation: Count the number of 0s, 1s, and 2s in one pass. Then overwrite the array in a second pass by placing the right number of 0s, 1s, and 2s.
- Time Complexity:Β O(n) β 2 passes through the array.
- Space Complexity:Β O(1) β constant space for counters.
- Example/Dry Run:
Input: [2, 0, 2, 1, 1, 0]Step 1: Count β count_0 = 2, count_1 = 2, count_2 = 2Step 2: Overwrite:[0, 0, 1, 1, 2, 2]
3οΈβ£ Optimal Approach
- Explanation:Β Use the Dutch National Flag algorithm with three pointers (low, mid, high). Rearrange elements in a single pass.
- Time Complexity:Β O(n) β single pass.
- Space Complexity:Β O(1) β in-place.
- Example/Dry Run:
Input: [2, 0, 2, 1, 1, 0]Initial: low = 0, mid = 0, high = 5
Step-by-step:mid = 0, nums[mid] = 2 β swap(nums[mid], nums[high]) β high--mid = 0, nums[mid] = 0 β swap(nums[low], nums[mid]) β low++, mid++mid = 1, nums[mid] = 0 β swap(nums[low], nums[mid]) β low++, mid++mid = 2, nums[mid] = 2 β swap(nums[mid], nums[high]) β high--mid = 2, nums[mid] = 1 β mid++mid = 3, nums[mid] = 1 β mid++
Final Output: [0, 0, 1, 1, 2, 2]
π Complexity Analysis
Approach | Time Complexity | Space Complexity |
---|---|---|
Brute Force | O(n log n) | O(1) |
Counting | O(n) | O(1) |
Dutch Flag (Optimal) | O(n) | O(1) |
π Optimization Ideas
The Dutch National Flag algorithm is already optimal β it solves the problem in a single traversal with constant space. No further optimization is necessary.
π Example Walkthroughs & Dry Runs
Example:Input: [2, 0, 1]Initial: low = 0, mid = 0, high = 2
1. nums[mid] = 2 β swap(nums[mid], nums[high]) β [1, 0, 2], high--2. nums[mid] = 1 β mid++3. nums[mid] = 0 β swap(nums[low], nums[mid]) β [0, 1, 2], low++, mid++
Output: [0, 1, 2]
π Additional Resources
Author: Neha Amin Date: 19/07/2025