Given a list of numbers with only 3 unique numbers(1, 2, 3), sort the list in O(n) time. Plus sort the array using constant space O(1).
Example:
Input: [3, 3, 2, 1, 3, 2, 1]
Output: [1, 1, 2, 2, 3, 3, 3]
Here the solution i made (is no O(1) space and have empty spaces spaces in the array..): What does this function is simple .. increases the size of the arrangement to double in the case that all its elements are 2; Then it goes to its previous length (current/2) to sort its elements .. if it is 1 it does nothing, if it finds a 2 it puts it in the previous maximum length + 1, it increases the variable len and eliminates the element and if it is 3 push and delete the element .. then you have empty spaces in the array and you don't meet the plus of the problem but it's O(n).
function sort(list) {
let len = list.length;
list.length=len*2
for(let i=0; i<list.length/2; i++){
let n=list[i]
if(n==2){
list[len]=n
delete list[i]
len++
}else if(n==3){
list.push(n)
delete list[i]
}
}
return list
}
console.log(sort([1,2,3,2,1,1]))