Skip to content
Related Articles

Related Articles

Improve Article

Convert an array to reduced form | Set 1 (Simple and Hashing)

  • Difficulty Level : Easy
  • Last Updated : 07 Jul, 2021

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. 

Input:  arr[] = {10, 40, 20}
Output: arr[] = {0, 2, 1}

Input:  arr[] = {5, 10, 40, 30, 20}
Output: arr[] = {0, 1, 4, 3, 2}

The expected time complexity is O(n Log n).

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.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

We strongly recommend that you click here and practice it, before moving on to the solution.

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).

Below are implementations of the above idea. 

C++




// C++ program to convert an array in reduced
// form
#include <bits/stdc++.h>
using namespace std;
 
void convert(int arr[], int n)
{
    // Create a temp array and copy contents
    // of arr[] to temp
    int temp[n];
    memcpy(temp, arr, n*sizeof(int));
 
    // Sort temp array
    sort(temp, temp + n);
 
    // Create a hash table. Refer
    unordered_map<int, int> umap;
 
    // One by one insert elements of sorted
    // temp[] and assign them values from 0
    // to n-1
    int val = 0;
    for (int i = 0; i < n; i++)
        umap[temp[i]] = val++;
 
    // Convert array by taking positions from
    // umap
    for (int i = 0; i < n; i++)
        arr[i] = umap[arr[i]];
}
 
void printArr(int arr[], int n)
{
    for (int i=0; i<n; i++)
        cout << arr[i] << " ";
}
 
// Driver program to test above method
int main()
{
    int arr[] = {10, 20, 15, 12, 11, 50};
    int n = sizeof(arr)/sizeof(arr[0]);
 
    cout << "Given Array is \n";
    printArr(arr, n);
 
    convert(arr , n);
 
    cout << "\n\nConverted Array is \n";
    printArr(arr, n);
 
    return 0;
}

Java




// Java Program to convert an Array
// to reduced form
import java.util.*;
 
class GFG
{
    public static void convert(int arr[], int n)
    {
        // Create a temp array and copy contents
        // of arr[] to temp
        int temp[] = arr.clone();
 
        // Sort temp array
        Arrays.sort(temp);
 
        // Create a hash table.
        HashMap<Integer, Integer> umap = new HashMap<>();
 
        // One by one insert elements of sorted
        // temp[] and assign them values from 0
        // to n-1
        int val = 0;
        for (int i = 0; i < n; i++)
            umap.put(temp[i], val++);
 
        // Convert array by taking positions from
        // umap
        for (int i = 0; i < n; i++)
            arr[i] = umap.get(arr[i]);
    }
 
    public static void printArr(int arr[], int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        int arr[] = {10, 20, 15, 12, 11, 50};
        int n = arr.length;
 
        System.out.println("Given Array is ");
        printArr(arr, n);
 
        convert(arr , n);
 
        System.out.println("\n\nConverted Array is ");
        printArr(arr, n);
 
    }
}
 
// This code is contributed by Abhishek Panwar

Python3




# Python3 program to convert an array
# in reduced form
def convert(arr, n):
    # Create a temp array and copy contents
    # of arr[] to temp
    temp = [arr[i] for i in range (n) ]
     
    # Sort temp array
    temp.sort()
     
    # create a map
    umap = {}
     
     
    # One by one insert elements of sorted
    # temp[] and assign them values from 0
    # to n-1
    val = 0
    for i in range (n):
        umap[temp[i]] = val
        val += 1
     
    # Convert array by taking positions from umap
    for i in range (n):
        arr[i] = umap[arr[i]]
     
def printArr(arr, n):
    for i in range(n):
        print(arr[i], end = " ")
 
# Driver Code
if __name__ == "__main__":
    arr = [10, 20, 15, 12, 11, 50]
    n = len(arr)
    print("Given Array is ")
    printArr(arr, n)
    convert(arr , n)
    print("\n\nConverted Array is ")
    printArr(arr, n)
 
# This code is contributed by Abhishek Gupta

C#




// C# Program to convert an Array
// to reduced form
using System;
using System.Collections.Generic;
using System.Linq;
 
class GFG
{
    public static void convert(int []arr, int n)
    {
        // Create a temp array and copy contents
        // of []arr to temp
        int []temp = new int[arr.Length];
        Array.Copy(arr, 0, temp, 0, arr.Length);
 
        // Sort temp array
        Array.Sort(temp);
 
        // Create a hash table.
        Dictionary<int, int> umap =
            new Dictionary<int, int>();
 
        // One by one insert elements of sorted
        // []temp and assign them values from 0
        // to n - 1
        int val = 0;
        for (int i = 0; i < n; i++)
            if(umap.ContainsKey(temp[i]))
                umap[temp[i]] = val++;
            else
                umap.Add(temp[i], val++);
 
        // Convert array by taking positions from
        // umap
        for (int i = 0; i < n; i++)
            arr[i] = umap[arr[i]];
    }
 
    public static void printArr(int []arr, int n)
    {
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
    }
 
    // Driver code
    public static void Main(String[] args)
    {
 
        int []arr = {10, 20, 15, 12, 11, 50};
        int n = arr.Length;
 
        Console.WriteLine("Given Array is ");
        printArr(arr, n);
 
        convert(arr , n);
 
        Console.WriteLine("\n\nConverted Array is ");
        printArr(arr, n);
    }
}
 
// This code is contributed by PrinciRaj1992

Javascript




<script>
 
// Javascript Program to convert an Array
// to reduced form
 
    function convert(arr, n)
    {
        // Create a temp array and copy contents
        // of arr[] to temp
        let temp = [...arr];
   
        // Sort temp array
        temp.sort((a, b) => a - b);
   
        // Create a hash table.
        let umap = new Map();
   
        // One by one insert elements of sorted
        // temp[] and assign them values from 0
        // to n-1
        let val = 0;
        for (let i = 0; i < n; i++)
            umap.set(temp[i], val++);
   
        // Convert array by taking positions from
        // umap
        for (let i = 0; i < n; i++)
            arr[i] = umap.get(arr[i]);
    }
   
    function prletArr(arr, n)
    {
        for (let i = 0; i < n; i++)
            document.write(arr[i] + " ");
    }
 
// Driver program
 
         let arr = [10, 20, 15, 12, 11, 50];
        let n = arr.length;
   
        document.write("Given Array is " + "<br/>");
        prletArr(arr, n);
   
        convert(arr , n);
   
        document.write("<br/>" + "Converted Array is "  + "<br/>");
        prletArr(arr, n);
       
</script>

Output:  

Given Array is 
10 20 15 12 11 50 

Converted Array is 
0 4 3 2 1 5 

Convert an array to reduced form | Set 2 (Using vector of pairs)
 

This article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :