Logo

Kode$word

Sort Colors

Sort Colors

LeetCode question 75 Medium

42 views
0
0

LeetCode Problem 75

Link of the Problem to try -: Link

Problem Statement :- 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.

Example 1:

Input: nums = [2,0,2,1,1,0]

Output: [0,0,1,1,2,2]

Example 2:

Input: nums = [2,0,1]

Output: [0,1,2]

You must solve this problem without using the library's sort function.

My Approach (1)

I have solved this question via my approach by counting frequency of each element like 0,1 and 2 as I avoid to use nested loops but i used for loops multiple times but as loops are used in a constant space of time that's why they did not increases the time complexity that's why my solution time complexity is O(n) even though I need to traverse array multiple time.

Here is the Approach:

int zeroCounter= 0;
int oneCounter = 0;
int twoCounter=0;
int counter =0;
for(int i =0; i< nums.length; i++){
if(nums[i] == 0){
zeroCounter++;
}else if(nums[i] == 1){
oneCounter++;
}else{
twoCounter++;
}
}

for(int i=0; i<zeroCounter;i++){
nums[i] = 0;
counter++;
}
for(int i=0; i<oneCounter;i++){
nums[counter] = 1;
counter++;
}
for(int i=0; i<twoCounter;i++){
nums[counter] = 2;
counter++;
}



My Approach (2)

This approach uses a algorithm called DNF (Dutch National Flag) Algorithm in this algorithm we have to focus on two elements out of three and make sure those two element are on the correct place as the last one came automatically to the correct position even though my approach(1) is uses loops multiple time but this approach is also take O(n) time complexity but uses loop one time that's why this approach is far cleaner than approach (1).

int low =0;
int high= nums.length-1;
int curr =0;
while(curr <= high){
if(nums[curr] == 0){
int temp = nums[low];
nums[low] = nums[curr];
nums[curr] = temp;
low++;
curr++;
}else if( nums[curr] == 1){
curr++;
}else{
int temp = nums[curr];
nums[curr] = nums[high];
nums[high] = temp;
high--;
}
}