Given an array with n distinct elements, convert the given array to a form where all elements are in the range from 0 to n-1. The order of elements is the same, i.e., 0 is placed in the place of the smallest element, 1 is placed for the second smallest element, … n-1 is placed for the largest element.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Method 1 (Simple) A simple solution is to first find the minimum element, replace it with 0, consider the remaining array and find the minimum in the remaining array and replace it with 1, and so on. The time complexity of this solution is O(n2)
Method 2 (Efficient) The idea is to use hashing and sorting. Below are the steps. 1) Create a temp array and copy the contents of the 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 from left to right and store mapping of numbers and their values (in converted array) in the hash table. This takes O(n) time on average. 5) Traverse given array and change elements to their positions using a hash table. This takes O(n) time on average.
The overall time complexity of this solution is O(n Log n).