Given an array with n distinct elements, convert the given array to a form where all elements are in range from 0 to n-1. The order of elements is same, i.e., 0 is placed in place of smallest element, 1 is placed for second smallest element, … n-1 is placed for largest element.
Method 1 (Simple)
A Simple Solution is to first find minimum element replace it with 0, consider remaining array and find minimum in the remaining array and replace it with 1 and so on. Time complexity of this solution is O(n2)
Method 2 (Efficient)
The idea is to use hashing and sorting. Below are steps. 1) Create a temp array and copy contents of given array to temp. This takes O(n) time. 2) Sort temp in ascending order. This takes O(n Log n) time. 3) Create an empty hash table. This takes O(1) time. 4) Traverse temp form left to right and store mapping of numbers and their values (in converted array) in hash table. This takes O(n) time on average. 5) Traverse given array and change elements to their positions using hash table. This takes O(n) time on average.
Overall time complexity of this solution is O(n Log n).