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

Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Input: nums = [2,0,1]
Output: [0,1,2]
Follow up:

Could you come up with a one-pass algorithm using only constant extra space?

Contents

In this approach, we will first count number of 0's, 1's and 2's in the input array nums and then place them in the order back into the input array.

import java.util.Arrays; public class SortColors { static int[] countOccurrencesAndAddThemToResult(int[] nums) { // first count 0's, 1's and 2's, below we are counting just zeros and ones, // any remaining are twos int zeros = 0; int ones = 0; for (int num : nums) { if (num == 0) { zeros++; } else if (num == 1) { ones++; } } // once we know how many 0's, 1's and 2's are there, place them back into the array. for (int i = 0; i < nums.length; i++) { if (i < zeros) { nums[i] = 0; } else if (i < zeros+ones) { nums[i] = 1; } else { nums[i] = 2; } } return nums; } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the input array nums length.
Space complexity: O(1)

In this approach, we will use two pointers to indicate left and right ends of the array and another pointer to indicate the current position of array that will go through from left to right. Then move all 0's to the left side, 2's to the right side and bring 1's to the middle.

implementation details:

Let's look at an example, say if the given input array is nums = [2,0,2,1,1,0]

import java.util.Arrays; public class SortColors { static int[] usingTwoPointers(int[] nums) { int left= 0; int right = nums.length -1; int current = 0; while(current<=right) { if(nums[current] == 0){ int temp = nums[left]; nums[left] = nums[current]; nums[current] = temp; left++; current++; } else if (nums[current] ==1) { current++; } else { int temp = nums[right]; nums[right] = nums[current]; nums[current] = temp; right--; } } return nums; } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the input array nums length.
Space complexity: O(1)

Above implementations source code can be found at GitHub link for Java code