I'm trying to solve the following question:
Given an array of numbers with only 3 unique numbers (1, 2, 3), sort the list in O(n) time.
Example 1:
Input: [3, 3, 2, 1, 3, 2, 1]
Output: [1, 1, 2, 2, 3, 3, 3]
Challenge: Try sorting the list using constant space
The first part where I can use extra space is easy, basically what I did is find the min,max and the middle value store them as keys in a hashmap
and their frequencies as the hashmap
values, and then fill the new created array with the correct values:
import java.util.Map;
import java.util.HashMap;
class Testing{
public static void sortArr(int[] arr){
int[] newArr=new int[arr.length];
Map<Integer,Integer> hm=new HashMap<Integer,Integer>(3);
int mini=minArr(arr);
int maxi=maxArr(arr);
int midNum=Integer.MAX_VALUE;
for(int num : arr){
if(hm.containsKey(num)){
hm.put(num,hm.get(num)+1);
}else{hm.put(num,1);}
}
for(int num : hm.keySet()){
if(num!=mini && num!=maxi){
midNum=num;
break;
}
}
for(int i=0;i<arr.length;++i){
if(i<hm.get(mini)){
newArr[i]=mini;
}else if(i>(arr.length-hm.get(maxi))){
newArr[i]=maxi;
}else{
newArr[i]=midNum;
}
}
for(int num : newArr){
System.out.println(num);
}
}
public static int minArr(int[] arr){
int mini=Integer.MAX_VALUE;
for(int num : arr){
if(num<mini){
mini=num;
}
}
return mini;
}
public static int maxArr(int[] arr){
int maxi=Integer.MIN_VALUE;
for(int num : arr){
if(num>maxi){
maxi=num;
}
}
return maxi;
}
public static void main(String args[]){
int[] arr={-4,-4,9,9,-4,3,9,3,3,3,3,9,9,-4,9,3};
sortArr(arr);
}
}
What I'm interested is the Challenge part, which I'm unable to solve, any help is appreciated, thanks.