Convert an Array to reduced form using Hashing
Last Updated :
08 Oct, 2023
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.
Examples:
Input: arr[] = {10, 40, 20}
Output: arr[] = {0, 2, 1}
Input: arr[] = {5, 10, 40, 30, 20}
Output: arr[] = {0, 1, 4, 3, 2}
Naive Approach:
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.
- Iterate over the array
- Find the minimum element and keep its position of occurrence.
- Update the result at the minimum index element with the new Position
- Increment the new position by 1.
- Update the original element at the current minimum element with the maximum value possible, so that it won't be minimum in a further iteration
- Return the result
Below is the implementation of the above approach:
C++
// C++ program to convert an array in reduced
// form
#include <bits/stdc++.h>
using namespace std;
vector<int> convert(vector<int>& arr)
{
int n = arr.size();
vector<int> result(n);
int currPos = 0;
// Iterate over the array
for (int i = 0; i < n; i++) {
int minn = INT_MAX;
int idx = -1;
// Find the minimum element and keep
// its position of occurrence
for (int j = 0; j < n; j++) {
if (minn > arr[j]) {
minn = arr[j];
idx = j;
}
}
// Update the result at minimum index element
// with new Position
result[idx] = currPos;
// Increment the new position
currPos++;
// Update the original element at current minimum
// element with maximum value possible, so that it
// won't be minimum in further iteration
arr[idx] = INT_MAX;
}
// Return the result
return result;
}
void printArr(vector<int>& arr)
{
for (auto i : arr) {
cout << i << " ";
}
}
// Driver program to test above method
int main()
{
vector<int> arr = { 10, 20, 15, 12, 11, 50 };
int n = arr.size();
cout << "Given Array is \n";
printArr(arr);
vector<int> result = convert(arr);
cout << "\n\nConverted Array is \n";
printArr(result);
return 0;
}
Java
import java.util.*;
import java.io.*;
public class Gfg {
static int[] convert(int[] arr)
{
int n = arr.length;
int[] result = new int[n];
int currPos = 0;
// Iterate over the array
for (int i = 0; i < n; i++) {
int minn = Integer.MAX_VALUE;
int idx = -1;
// Find the minimum element and keep
// its position of occurrence
for (int j = 0; j < n; j++) {
if (minn > arr[j]) {
minn = arr[j];
idx = j;
}
}
// Update the result at minimum index element
// with new Position
result[idx] = currPos;
// Increment the new position
currPos++;
// Update the original element at current
// minimum element with maximum value possible,
// so that it won't be minimum in further
// iteration
arr[idx] = Integer.MAX_VALUE;
}
// Return the result
return result;
}
static void printArr(int[] arr)
{
for (int i : arr) {
System.out.print(i + " ");
}
}
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);
int[] result = convert(arr);
System.out.println("\n\nConverted Array is");
printArr(result);
}
}
Python3
from typing import List
import sys
def convert(arr: List[int])->List[int]:
n = len(arr)
result = [0]*n
curr_pos = 0
# Iterate over the array
for i in range(n):
minn = sys.maxsize
idx = -1
# Find the minimum element and keep
# its position of occurrence
for j in range(n):
if (minn > arr[j]):
minn = arr[j]
idx = j
# Update the result at minimum index element
# with new Position
result[idx] = curr_pos
# Increment the new position
curr_pos += 1
# Update the original element at current minimum
# element with maximum value possible, so that it
# won't be minimum in further iteration
arr[idx] = sys.maxsize
# Return the result
return result
def printArr(arr: List[int]):
for i in arr:
print(i, end=" ")
# Driver program to test above method
if __name__ == '__main__':
arr = [10, 20, 15, 12, 11, 50]
n = len(arr)
print("Given Array is ")
printArr(arr)
result = convert(arr)
print("\n\nConverted Array is ")
printArr(result)
C#
using System;
class Gfg
{
static int[] Convert(int[] arr)
{
int n = arr.Length;
int[] result = new int[n];
int currPos = 0;
// Iterate over the array
for (int i = 0; i < n; i++)
{
int minn = int.MaxValue;
int idx = -1;
// Find the minimum element and keep
// its position of occurrence
for (int j = 0; j < n; j++)
{
if (minn > arr[j])
{
minn = arr[j];
idx = j;
}
}
// Update the result at minimum index element
// with new Position
result[idx] = currPos;
// Increment the new position
currPos++;
// Update the original element at current
// minimum element with maximum value possible,
// so that it won't be minimum in further
// iteration
arr[idx] = int.MaxValue;
}
// Return the result
return result;
}
static void PrintArr(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i] + " ");
}
}
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);
int[] result = Convert(arr);
Console.WriteLine("\n\nConverted Array is");
PrintArr(result);
}
}
// This code is contributed by hkdass001.
JavaScript
// Javascript program to convert an array in reduced form
function convert(arr)
{
let n = arr.length;
let result=new Array(n);
let currPos = 0;
// Iterate over the array
for (let i = 0; i < n; i++) {
let minn = Number.MAX_SAFE_INTEGER;
let idx = -1;
// Find the minimum element and keep
// its position of occurrence
for (let j = 0; j < n; j++) {
if (minn > arr[j]) {
minn = arr[j];
idx = j;
}
}
// Update the result at minimum index element
// with new Position
result[idx] = currPos;
// Increment the new position
currPos++;
// Update the original element at current minimum
// element with maximum value possible, so that it
// won't be minimum in further iteration
arr[idx] = Number.MAX_SAFE_INTEGER;
}
// Return the result
return result;
}
function printArr(arr)
{
for (let i=0; i<arr.length; i++) {
document.write(arr[i] + " ");
}
}
// Driver program to test above method
let arr = [ 10, 20, 15, 12, 11, 50 ];
let n = arr.length;
document.write("Given Array is");
printArr(arr);
let result = convert(arr);
document.write("Converted Array is ");
printArr(result);
OutputGiven Array is
10 20 15 12 11 50
Converted Array is
0 4 3 2 1 5
Time complexity: O(N2)
Auxiliary space: O(N)
Efficient Approach:
The idea is to sort the given array and use an unordered map to store the reduced form of each value of array then update the whole array to its reduced form using values from unordered map.
Follow the below steps to implement the idea:
- Create a temp array and copy the contents of the given array to temp[].
- Sort temp[] in ascending order.
- Create an empty hash table.
- Traverse temp[] from left to right and store mapping of numbers and their values (in converted array) in the hash table.
- Traverse given array and change elements to their positions using a hash table.
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
// http://tinyurl.com/zp5wgef
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>
OutputGiven Array is
10 20 15 12 11 50
Converted Array is
0 4 3 2 1 5
Time complexity: O(N * log N)
Auxiliary Space: O(N)
Using priority_queue and hashmap:
The idea is to sort the given array using priority_queue instead of calling sort stl and use an unordered map to store the reduced form of each value of array then update the whole array to its reduced form using values from unordered map.
Algorithm:
- Create a priority_queue pq to get the sorted version of arr in increasing order.
- Push the values of arr in the priority queue.
- Create a temp array and copy the contents of the priority_queue to temp[].
- Create an empty hash table.
- Traverse temp[] from left to right and store mapping of numbers and their values (in converted array) in the hash table.
- Traverse given array and change elements to their positions using a hash table.
Below is the implementation of the approach:
C++
// C++ program to convert an array in reduced
// form
#include <bits/stdc++.h>
using namespace std;
// Function to convert an array in reduced
// form
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));
// prioirty queue to get array sorted
// in increasing order
priority_queue<int, vector<int>, greater<int>> pq;
for( int i = 0; i < n; i++)
pq.push( arr[i] );
int i = 0;
// taking elements from priority queue
// to temp array
while(!pq.empty()) {
temp[i++] = pq.top();
pq.pop();
}
// Create a hash table. Refer
// http://tinyurl.com/zp5wgef
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 in reduced
// form
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
// Function to convert an array in reduced
// form
class Gfg {
public static void convert(int[] arr, int n) {
// Create a temp array and copy contents
// of arr[] to temp
int[] temp = Arrays.copyOf(arr, n);
// prioirty queue to get array sorted
// in increasing order
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int i = 0; i < n; i++) {
pq.offer(arr[i]);
}
int i = 0;
// taking elements from priority queue
// to temp array
while (!pq.isEmpty()) {
temp[i++] = pq.poll();
}
// Create a hash table. Refer
// http://tinyurl.com/zp5wgef
Map<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 (i = 0; i < n; i++) {
umap.put(temp[i], val++);
}
// Convert array by taking positions from
// umap
for (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 program to test above method
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);
}
}
Python3
import heapq # Import heapq for the priority queue data structure
# Function to convert an array into its reduced form
def convert(arr):
n = len(arr) # Get the length of the input array
# Create a temporary list and copy the contents of arr to it
temp = list(arr)
# Create a priority queue to get the array sorted in increasing order
# using heapq module
pq = []
for i in range(n):
heapq.heappush(pq, arr[i])
i = 0
# Taking elements from priority queue to temp list
while len(pq) != 0:
temp[i] = heapq.heappop(pq)
i += 1
# Create a dictionary to store the index of each element in the sorted list
umap = {}
# Assign ranks to the elements of the sorted list
val = 0
for i in range(n):
umap[temp[i]] = val
val += 1
# Replace each element of the input array with its rank in the dictionary
for i in range(n):
arr[i] = umap[arr[i]]
# Driver code to test the convert function
if __name__ == "__main__":
arr = [10, 20, 15, 12, 11, 50]
print("Given array is")
print(arr)
convert(arr)
print("\nConverted array is")
print(arr)
C#
using System;
using System.Collections.Generic;
class GFG
{
// Function to convert an array in reduced form
static void Convert(int[] arr, int n)
{
// Create a temp array and copy contents
// of arr[] to temp
int[] temp = new int[n];
Array.Copy(arr, temp, n);
// Sorted array using Priority Queue
// to get array sorted in increasing order
var pq = new SortedSet<int>(temp);
int i = 0;
// Taking elements from the sorted set
// and assigning them values from 0 to n-1
foreach (var num in pq)
{
temp[i++] = num;
}
// Create a dictionary (hash table)
// to store the positions of elements
var dict = new Dictionary<int, int>();
// Assigning positions to elements in the sorted array
int val = 0;
foreach (var num in temp)
{
if (!dict.ContainsKey(num))
{
dict[num] = val++;
}
}
// Convert array by taking positions from the dictionary
for (int j = 0; j < n; j++)
{
arr[j] = dict[arr[j]];
}
}
// Function to print the array
static void PrintArr(int[] arr)
{
foreach (int num in arr)
{
Console.Write(num + " ");
}
}
// Driver program to test the above method
static void Main()
{
int[] arr = { 10, 20, 15, 12, 11, 50 };
int n = arr.Length;
Console.WriteLine("Given Array is:");
PrintArr(arr);
// Console.WriteLine("\n");
Convert(arr, n);
Console.WriteLine("\n\nConverted Array is:");
PrintArr(arr);
}
}
JavaScript
// Function to convert an array in reduced form
function convert(arr) {
// Create a copy of the array
let temp = arr.slice();
// Sort the copy in increasing order
temp.sort((a, b) => a - b);
// Create a map to store original indices
let umap = new Map();
// Assign values from 0 to n-1
for (let i = 0; i < arr.length; i++) {
umap.set(temp[i], i);
}
// Convert the array using the map
for (let i = 0; i < arr.length; i++) {
arr[i] = umap.get(arr[i]);
}
}
function printArr(arr) {
for (let i = 0; i < arr.length; i++) {
console.log(arr[i] + " ");
}
}
// Driver program to test above method
let arr = [10, 20, 15, 12, 11, 50];
console.log("Given Array is:");
printArr(arr);
convert(arr);
console.log("\nConverted Array is:");
printArr(arr);
OutputGiven Array is
10 20 15 12 11 50
Converted Array is
0 4 3 2 1 5
Time Complexity: O(N * log N) as insertion of N elements in priority_queue takes N*logN time. Here, N is size of the input array.
Space Complexity: O(N) as priority_queue pq and temp array has been created.
Convert an array to reduced form | Set 2 (Using vector of pairs)
Similar Reads
Convert an Array to reduced form using Vector of pairs
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. Input: arr[] = {10,
11 min read
Convert an Array to reduced for using Binary Search
Given an array arr[] consisting of N distinct integers, the task is to convert the given array into a sequence of first N non-negative integers, i.e. [0, N - 1] such that the order of the elements is the same, i.e. 0 is placed at the index of the smallest array element, 1 at the index of the second
6 min read
Minimum length of the reduced Array formed using given operations
Given an array arr of length N, the task is to minimize its length by performing following operations: Remove any adjacent equal pairs, ( i.e. if arr[i] = arr[i+1]) and replace it with single instance of arr[i] + 1.Each operation decrements the length of the array by 1.Repeat the operation till no m
10 min read
Classify strings from an array using Custom Hash Function
Given an array of strings arr[] consisting of N strings, the task is to categorize the strings according to the hash value obtained by adding ASCII values % 26 of the characters in the string. Examples: Input: arr[][] = {"geeks", "for", "geeks"}Output:geeks geeksforExplanation:The hash value of stri
8 min read
How to Convert HashMap to ArrayList in Java?
In Java a HashMap is a collection that stores key-value pairs on the other hand, an ArrayList is a collection that stores dynamic arrays. There are some scenarios where we need to convert a HashMap into an ArrayList such as:Extracting only the keys or values in the list form.Converting key-value pai
2 min read
Minimize cost to convert all array elements to 0
Given two integers X and Y and a binary array arr[] of length N whose first and last element is 1, the task is to minimize the cost to convert all array elements to 0, where X and Y represent the cost of converting a subarray of all 1s to 0s and the cost of converting any element to 0 respectively.
12 min read
Convert given Array of Integers into Words
Given an array arr[] of N elements which are in range [0, 9]. the task is to convert each array element into its numeric strings. Examples: Input: arr[] = [1, 4, 3, 2, 6]Output: one four three two six Input: arr[]= [0, 4, 4, 6, 9]Output: zero four four six nine Approach: The problem can be solved wi
4 min read
Reduce all array elements to zero by performing given operations thrice
Given an array arr[] of size N, the task is to convert every array element to 0 by applying the following operations exactly three times: Select a subarray.Increment every element of the subarray by the integer multiple of its length. Finally, print the first and last indices of the subarray involve
9 min read
Minimum removals required to convert given array to a Mountain Array
Given an array arr[] consisting of N integers???, the task is to find the minimum number of array elements required to be removed to make the given array a mountain array. A mountain array has the following properties: Length of the array ? 3.There exists some index i (0-based indexing) with 0 <
15+ min read
Reduce array to a single element by repeatedly removing an element from any increasing pair
Given an array arr[] consisting of permutation in the range [1, N], the task is to check if the given array can be reduced to a single non-zero element by performing the following operations: Select indices i and j such that i < j and arr[i] < arr[j] and convert one of the two elements to 0. I
9 min read