position - IN3
In one of my coding round i was asked below question. Interviewer were expecting solution with O(n) time complexity with in-place.
The best solution i think is O(n*r) with in-place (used enhance of Dutch National Flag https://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/). Please help me to find O(n) solution. is O(n) solution possible with in-place?
where n is Array length
And r is types of unique elements in array
Question -
Given an array nums with 'n' objects of 'r' types , sort them in-place so that objects of the same type are adjacent and are in the order provided. You must solve this problem without using the library's sort function.
1<= n <= 1000
1<= r <=50
Example 1:
Consider a shelf in walmart which has inventory of type bread, chocolate, or chips
r = 3
Rearrange the shelf in the order bread, chocolate, and chips.
We will use the integers 0, 1, and 2 to represent the color bread, chocolate, and chips, respectively.
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Input: nums = [2,0,1]
Output: [0,1,2]
Example 2:
Consider a shelf in walmart which has inventory of type cookie ,gum ,bread, chocolate, and chips
r = 5
Rearrange the shelf in the order gum, cookie, bread, chocolate and chips .
We will use the integers 0, 1, and 2 ,3, 4 to represent gum, cookie, bread, chocolate and chips.
Input: nums = [2,4,3,1,2,4,0,2,1,3,4,2,1]
Output: [0,1,1,1,2,2,2,2,3,3,4,4,4]
Answer with O(n*r)
void sortWithDutchNationalFlag(int[] nums, int r){
int so = 0;
int n = nums.length;
for(int k = r-1 ; k>0 ; k--){
int sb = 0 ;
for(int i = 0 ; i< n-so; i++){
if(nums[i] == k){
sb++;
}
else if(sb > 0){
nums[i - sb] = nums[i];
nums[i] = k;
}
}
so += sb;
}
}
