There is a char array of n length. The array can have elements only from any order of R, B, W. You need to sort the array so that order should R,B,W (i.e. all R will come first followed by B and then W).
Constraints: Time complexity is O(n) and space complexity should be O(1).
Assumption: You can assume one swap method is given with signature
swap(char[] arr, int index1, int index2)
that swaps number in unit time. Method given to implement:public sort(char[]array);
Here is my implementation of it. A better solution from anyone is appreciated. Anyone is free to point out any mistakes.
public static void sort(char[] arr){
int rIndex = 0, wIndex = arr.length -1;
for (int i = 0 ; i <= wIndex;){
if ( arr[i] == 'R' ){
swap(arr, i , rIndex ++ );
i ++;
} else if (arr[i] == 'W' ){
swap(arr, i , wIndex -- );
}else{
i ++;
}
}
}
"WRB"
gives"RWB"
. \$\endgroup\$i <= wIndex
termination. \$\endgroup\$"WBRWBRBWRB"
yields"RRBRBBBWWW"
. \$\endgroup\$