I am actually thinking of having the problem solved using a TreeMap which holds the keys in ascending order and can store the indexes as the value for the key. In that way, we can have the duplicate values indexed properly and I suppose solving the problem using a TreeMap should have O(n log n) complexity.
Here is my working code in Java.
import java.util.*;
public class HelloWorld {
public static void main(String []args){
int arr[] = {530, 0, 24, 335, 274, 591};
int sortedIndexes[] = getSortedIndexes(arr);
printSortedIndexes(sortedIndexes);
}
public static void printSortedIndexes(int[] printArr) {
for (int element : printArr) {
System.out.print(element + " ");
}
}
public static int[] getSortedIndexes (int[] arr) {
TreeMap<Integer, List<Integer>> map = new TreeMap<>();
for (int i = 0; i < arr.length; i++) {
if (map.containsKey(arr[i])) {
List<Integer> indexes = map.get(arr[i]);
indexes.add(i);
} else {
List<Integer> indexes = new ArrayList<>();
indexes.add(i);
map.put(arr[i], indexes);
}
}
// Now get the elements from the LinkedHashMap
int[] result = new int[arr.length];
int counter = 0;
for( Map.Entry<Integer, List<Integer>> entry : map.entrySet()) {
Integer key = entry.getKey();
List<Integer> indexes = entry.getValue();
for (int index : indexes) {
result[counter] = index;
counter++;
}
}
return result;
}
}
The TreeMap itself has O(log n) complexity for insertion and lookup. I am taking a map of <Integer, Lis<Integer>> so that we can store the values from the given array as keys and the indexes of the values as a List under that key (this is to handle the duplicate cases). If there is no duplicate in the input, we can get rid of the List<Integer> and just can have the TreeMap<Integer, Integer>.
I hope that helps.
O(n^3)complexity. It hasO((n) + (n log n) + (n)) = O(n log n)complexity. The firstmapisO(n), the sort isO(n log n), and the final map isO(n). When we add those steps together, the remaining complexity isn log n.