Problem
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 color red, white, and blue, respectively.
You must solve this problem without using the library’s sort function.
By the way this is Dutch National Flag - 🇳🇱.
Examples
Example 1:
| |
Example 2:
| |
Solution
The Dutch National Flag Algorithm sorts an array of red, blue, and white objects by separating them from each other based on their colors. Hence, we can adopt the algorithm to sort any array of three different kinds of objects / values.
Method 1 - Using 3-Way Partition Quicksort
3 way quick sort basically partitions the array in 3 parts:
- First part is lesser than the pivot -
arr[l..i] - Second part is equal to pivot -
arr[i+1..j-1] - Third part is greater than pivot -
arr[j..r]
Algorithm
l, r, and m are pointers used to separate the 0s, 1s, and 2s.
l (left) marks the end of the zone for 0s, m (middle) is the current index being checked, and r (right) marks the start of the zone for 2s.
Lets assume l is the left pointer, covering the 0s, r is the right pointer covering 2s and m is somewhere in the middle covering 1s.
- Start with
l=0,m=0andr = n - 1, wherenis length of array. - If the current element
nums[m]is0, it should be at the start of the array. We swap the current element with the element at thelpointer and then increase bothmandlpointers. This is safe because anything on the left ofmis already processed and confirmed not to be2. - If the current element
nums[m]is2, it should be at the end of the array. We swap the current element with the element at therpointer. Then we only decrement therpointer as the element atmcould be0and might need to be swapped with the element atl. Here, we do not immediately incrementmbecause the newly swapped element from positionrhasn’t been processed yet. - If the current element
nums[m]is1, then we just increment m, value is at correct place
Video Explanation
Here is the video explanation:
Code
| |
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(1)
Dry Run
| |
Iteration 1
| |
Iteration 2
| |
and so on.
Method 2 - Partition by Checking Low and High Values
This is similar to previous problem, but this will work for any 3 different numbers. In this problem, we know low=0 and high=, but if we don’t, this algorithm will help us out.
Code
| |
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(1)
Method 3 - Using 2 Pass Counting Sort
Code
| |
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(1)