Skip to content
Related Articles

Related Articles

Improve Article

Rearrange an array such that ‘arr[j]’ becomes ‘i’ if ‘arr[i]’ is ‘j’ | Set 1

  • Difficulty Level : Hard
  • Last Updated : 12 Apr, 2021

Given an array of size n where all elements are distinct and in range from 0 to n-1, change contents of arr[] so that arr[i] = j is changed to arr[j] = i. 
Examples: 
 

Example 1:
Input: arr[]  = {1, 3, 0, 2};
Output: arr[] = {2, 0, 3, 1};
Explanation for the above output.
Since arr[0] is 1, arr[1] is changed to 0
Since arr[1] is 3, arr[3] is changed to 1
Since arr[2] is 0, arr[0] is changed to 2
Since arr[3] is 2, arr[2] is changed to 3

Example 2:
Input: arr[]  = {2, 0, 1, 4, 5, 3};
Output: arr[] = {1, 2, 0, 5, 3, 4};

Example 3:
Input: arr[]  = {0, 1, 2, 3};
Output: arr[] = {0, 1, 2, 3};

Example 4:
Input: arr[]  = {3, 2, 1, 0};
Output: arr[] = {3, 2, 1, 0};

 

A Simple Solution is to create a temporary array and one by one copy ‘i’ to ‘temp[arr[i]]’ where i varies from 0 to n-1. 
Below is the implementation of the above idea. 
 

C++




// A simple C++ program to rearrange contents of arr[]
// such that arr[j] becomes j if arr[i] is j
#include <bits/stdc++.h>
using namespace std;
 
// A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]'
// becomes 'i' if 'arr[i]' is 'j'
void rearrangeNaive(int arr[], int n)
{
    // Create an auxiliary array of same size
    int temp[n], i;
 
    // Store result in temp[]
    for (i = 0; i < n; i++)
        temp[arr[i]] = i;
 
    // Copy temp back to arr[]
    for (i = 0; i < n; i++)
        arr[i] = temp[i];
}
 
// A utility function to print contents of arr[0..n-1]
void printArray(int arr[], int n)
{
    int i;
    for (i = 0; i < n; i++)
        cout << ("%d ", arr[i]);
    cout << ("\n");
}
 
// Driver code
int main()
{
    int arr[] = { 1, 3, 0, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << ("Given array is \n");
    printArray(arr, n);
 
    rearrangeNaive(arr, n);
 
    cout << ("Modified array is \n");
    printArray(arr, n);
    return 0;
}
 
// This code is contributed by Code_Mech

C




// A simple C program to rearrange contents of arr[]
// such that arr[j] becomes j if arr[i] is j
#include <stdio.h>
 
// A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]'
// becomes 'i' if 'arr[i]' is 'j'
void rearrangeNaive(int arr[], int n)
{
    // Create an auxiliary array of same size
    int temp[n], i;
 
    // Store result in temp[]
    for (i = 0; i < n; i++)
        temp[arr[i]] = i;
 
    // Copy temp back to arr[]
    for (i = 0; i < n; i++)
        arr[i] = temp[i];
}
 
// A utility function to print contents of arr[0..n-1]
void printArray(int arr[], int n)
{
    int i;
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}
 
// Driver program
int main()
{
    int arr[] = { 1, 3, 0, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    printf("Given array is \n");
    printArray(arr, n);
 
    rearrangeNaive(arr, n);
 
    printf("Modified array is \n");
    printArray(arr, n);
    return 0;
}

Java




// A simple Java program to rearrange contents of arr[]
// such that arr[j] becomes j if arr[i] is j
class RearrangeArray {
    // A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]'
    // becomes 'i' if 'arr[i]' is 'j'
    void rearrangeNaive(int arr[], int n)
    {
        // Create an auxiliary array of same size
        int temp[] = new int[n];
        int i;
 
        // Store result in temp[]
        for (i = 0; i < n; i++)
            temp[arr[i]] = i;
 
        // Copy temp back to arr[]
        for (i = 0; i < n; i++)
            arr[i] = temp[i];
    }
 
    // A utility function to print contents of arr[0..n-1]
    void printArray(int arr[], int n)
    {
        int i;
        for (i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println("");
    }
 
    // Driver program to test above functions
    public static void main(String[] args)
    {
        RearrangeArray arrange = new RearrangeArray();
        int arr[] = { 1, 3, 0, 2 };
        int n = arr.length;
 
        System.out.println("Given array is ");
        arrange.printArray(arr, n);
 
        arrange.rearrangeNaive(arr, n);
 
        System.out.println("Modified array is ");
        arrange.printArray(arr, n);
    }
}

Python3




# A simple Python3 program to rearrange
# contents of arr[] such that arr[j]
# becomes j if arr[i] is j
 
# A simple method to rearrange
# 'arr[0..n-1]' so that 'arr[j]'
# becomes 'i' if 'arr[i]' is 'j'
def rearrangeNaive(arr, n):
 
    # Create an auxiliary array
    # of same size
    temp = [0] * n
     
    # Store result in temp[]
    for i in range(0, n):
        temp[arr[i]] = i
 
    # Copy temp back to arr[]
    for i in range(0, n):
        arr[i] = temp[i]
 
 
    # A utility function to print
    # contents of arr[0..n-1]
def printArray(arr, n):
    for i in range(0, n):
        print(arr[i], end = " ")
 
# Driver program
arr = [1, 3, 0, 2]
n = len(arr)
print("Given array is", end = " ")
printArray(arr, n)
 
rearrangeNaive(arr, n)
print("\nModified array is", end = " ")
printArray(arr, n)
 
# This code is contributed by Smitha Dinesh Semwal

C#




// A simple C# program to rearrange contents of arr[]
// such that arr[j] becomes j if arr[i] is j
 
using System;
class RearrangeArray {
    // A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]'
    // becomes 'i' if 'arr[i]' is 'j'
    void rearrangeNaive(int[] arr, int n)
    {
        // Create an auxiliary array of same size
        int[] temp = new int[n];
        int i;
 
        // Store result in temp[]
        for (i = 0; i < n; i++)
            temp[arr[i]] = i;
 
        // Copy temp back to arr[]
        for (i = 0; i < n; i++)
            arr[i] = temp[i];
    }
 
    // A utility function to print contents of arr[0..n-1]
    void printArray(int[] arr, int n)
    {
        int i;
        for (i = 0; i < n; i++) {
            Console.Write(arr[i] + " ");
        }
        Console.WriteLine("");
    }
 
    // Driver program to test above functions
    public static void Main()
    {
        RearrangeArray arrange = new RearrangeArray();
        int[] arr = { 1, 3, 0, 2 };
        int n = arr.Length;
 
        Console.WriteLine("Given array is ");
        arrange.printArray(arr, n);
 
        arrange.rearrangeNaive(arr, n);
 
        Console.WriteLine("Modified array is ");
        arrange.printArray(arr, n);
    }
}

Javascript




<script>
 
// A simple JavaScript program to rearrange contents of arr[]
// such that arr[j] becomes j if arr[i] is j
 
// A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]'
// becomes 'i' if 'arr[i]' is 'j'
function rearrangeNaive(arr, n)
{
    // Create an auxiliary array of same size
    let temp = new Array(n), i;
 
    // Store result in temp[]
    for (i = 0; i < n; i++)
        temp[arr[i]] = i;
 
    // Copy temp back to arr[]
    for (i = 0; i < n; i++)
        arr[i] = temp[i];
}
 
// A utility function to print contents of arr[0..n-1]
function printArray(arr, n)
{
    let i;
    for (i = 0; i < n; i++)
        document.write(" " + arr[i]);
    document.write("<br>");
}
 
// Driver code
    let arr = [ 1, 3, 0, 2 ];
    let n = arr.length;
 
    document.write("Given array is <br>");
    printArray(arr, n);
 
    rearrangeNaive(arr, n);
 
    document.write("Modified array is <br>");
    printArray(arr, n);
 
// This code is contributed by Surbhi Tyagi.
 
</script>

Output: 

Given array is
1 3 0 2
Modified array is
2 0 3 1

The time complexity of the above solution is O(n) and auxiliary space needed is O(n).
Can we solve this in O(n) time and O(1) auxiliary space? 
The idea is based on the fact that the modified array is basically a permutation of the input array. We can find the target permutation by storing the next item before updating it. 
Let us consider array ‘{1, 3, 0, 2}’ for example. We start with i = 0, arr[i] is 1. So we go to arr[1] and change it to 0 (because i is 0). Before we make the change, we store the old value of arr[1] as the old value is going to be our new index i. In the next iteration, we have i = 3, arr[3] is 2, so we change arr[2] to 3. Before making the change we store next i as old value of arr[2]. 
The below code gives idea about this approach. 
 



// This function works only when output is a permutation
// with one cycle.
void rearrangeUtil(int arr[], int n)
{
    // 'val' is the value to be stored at 'arr[i]'
    int val = 0;   // The next value is determined
                  // using current index
    int i = arr[0];  // The next index is determined
                     // using current value

    // While all elements in cycle are not processed
    while (i != 0)
    {
        // Store value at index as it is going to be
        // used as next index
        int new_i = arr[i];

        // Update arr[]
        arr[i] = val;

        // Update value and index for next iteration
        val = i;
        i = new_i;
    }

    arr[0] = val;  // Update the value at arr[0]
}

The above function doesn’t work for inputs like {2, 0, 1, 4, 5, 3}; as there are two cycles. One cycle is (2, 0, 1) and other cycle is (4, 5, 3). 
How to handle multiple cycles with the O(1) space constraint? 
The idea is to process all cycles one by one. To check whether an element is processed or not, we change the value of processed items arr[i] as -arr[i]. Since 0 can not be made negative, we first change all arr[i] to arr[i] + 1. In the end, we make all values positive and subtract 1 to get old values back. 
 

C++




// A space efficient C++ program to rearrange contents of
// arr[] such that arr[j] becomes j if arr[i] is j
#include <iostream>
using namespace std;
 
// A utility function to rearrange elements in the cycle
// starting at arr[i]. This function assumes values in
// arr[] be from 1 to n. It changes arr[j-1] to i+1
// if arr[i-1] is j+1
void rearrangeUtil(int arr[], int n, int i)
{
    // 'val' is the value to be stored at 'arr[i]'
    int val = -(i + 1); // The next value is determined
    // using current index
    i = arr[i] - 1; // The next index is determined
    // using current value
 
    // While all elements in cycle are not processed
    while (arr[i] > 0)
    {
         
        // Store value at index as it is going to be
        // used as next index
        int new_i = arr[i] - 1;
 
        // Update arr[]
        arr[i] = val;
 
        // Update value and index for next iteration
        val = -(i + 1);
        i = new_i;
    }
}
 
// A space efficient method to rearrange 'arr[0..n-1]'
// so that 'arr[j]' becomes 'i' if 'arr[i]' is 'j'
void rearrange(int arr[], int n)
{
    // Increment all values by 1, so that all elements
    // can be made negative to mark them as visited
    int i;
    for (i = 0; i < n; i++)
        arr[i]++;
 
    // Process all cycles
    for (i = 0; i < n; i++)
    {
         
        // Process cycle starting at arr[i] if this cycle is
        // not already processed
        if (arr[i] > 0)
            rearrangeUtil(arr, n, i);
    }
 
    // Change sign and values of arr[] to get the original
    // values back, i.e., values in range from 0 to n-1
    for (i = 0; i < n; i++)
        arr[i] = (-arr[i]) - 1;
}
 
// A utility function to print contents of arr[0..n-1]
void printArray(int arr[], int n)
{
    int i;
    for (i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;
}
 
// Driver program
int main()
{
    int arr[] = { 2, 0, 1, 4, 5, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << "Given array is " << endl;
    printArray(arr, n);
 
    rearrange(arr, n);
 
    cout << "Modified array is " << endl;
    printArray(arr, n);
    return 0;
}
 
// This code is contributed by shubhamsingh10

C




// A space efficient C program to rearrange contents of
// arr[] such that arr[j] becomes j if arr[i] is j
#include <stdio.h>
 
// A utility function to rearrange elements in the cycle
// starting at arr[i]. This function assumes values in
// arr[] be from 1 to n.  It changes arr[j-1] to i+1
// if arr[i-1] is j+1
void rearrangeUtil(int arr[], int n, int i)
{
    // 'val' is the value to be stored at 'arr[i]'
    int val = -(i + 1); // The next value is determined
    // using current index
    i = arr[i] - 1; // The next index is determined
    // using current value
 
    // While all elements in cycle are not processed
    while (arr[i] > 0) {
        // Store value at index as it is going to be
        // used as next index
        int new_i = arr[i] - 1;
 
        // Update arr[]
        arr[i] = val;
 
        // Update value and index for next iteration
        val = -(i + 1);
        i = new_i;
    }
}
 
// A space efficient method to rearrange 'arr[0..n-1]'
// so that 'arr[j]' becomes 'i' if 'arr[i]' is 'j'
void rearrange(int arr[], int n)
{
    // Increment all values by 1, so that all elements
    // can be made negative to mark them as visited
    int i;
    for (i = 0; i < n; i++)
        arr[i]++;
 
    // Process all cycles
    for (i = 0; i < n; i++) {
        // Process cycle starting at arr[i] if this cycle is
        // not already processed
        if (arr[i] > 0)
            rearrangeUtil(arr, n, i);
    }
 
    // Change sign and values of arr[] to get the original
    // values back, i.e., values in range from 0 to n-1
    for (i = 0; i < n; i++)
        arr[i] = (-arr[i]) - 1;
}
 
// A utility function to print contents of arr[0..n-1]
void printArray(int arr[], int n)
{
    int i;
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}
 
// Driver program
int main()
{
    int arr[] = { 2, 0, 1, 4, 5, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    printf("Given array is \n");
    printArray(arr, n);
 
    rearrange(arr, n);
 
    printf("Modified array is \n");
    printArray(arr, n);
    return 0;
}

Java




// A space efficient Java program to rearrange contents of
// arr[] such that arr[j] becomes j if arr[i] is j
 
class RearrangeArray {
    // A utility function to rearrange elements in the cycle
    // starting at arr[i]. This function assumes values in
    // arr[] be from 1 to n.  It changes arr[j-1] to i+1
    // if arr[i-1] is j+1
    void rearrangeUtil(int arr[], int n, int i)
    {
        // 'val' is the value to be stored at 'arr[i]'
 
        // The next value is determined using current index
        int val = -(i + 1);
 
        // The next index is determined
        // using current value
        i = arr[i] - 1;
 
        // While all elements in cycle are not processed
        while (arr[i] > 0) {
            // Store value at index as it is going to be
            // used as next index
            int new_i = arr[i] - 1;
 
            // Update arr[]
            arr[i] = val;
 
            // Update value and index for next iteration
            val = -(i + 1);
            i = new_i;
        }
    }
 
    // A space efficient method to rearrange 'arr[0..n-1]'
    // so that 'arr[j]' becomes 'i' if 'arr[i]' is 'j'
    void rearrange(int arr[], int n)
    {
        // Increment all values by 1, so that all elements
        // can be made negative to mark them as visited
        int i;
        for (i = 0; i < n; i++)
            arr[i]++;
 
        // Process all cycles
        for (i = 0; i < n; i++) {
            // Process cycle starting at arr[i] if this cycle is
            // not already processed
            if (arr[i] > 0)
                rearrangeUtil(arr, n, i);
        }
 
        // Change sign and values of arr[] to get the original
        // values back, i.e., values in range from 0 to n-1
        for (i = 0; i < n; i++)
            arr[i] = (-arr[i]) - 1;
    }
 
    // A utility function to print contents of arr[0..n-1]
    void printArray(int arr[], int n)
    {
        int i;
        for (i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
        System.out.println("");
    }
 
    // Driver program
    public static void main(String[] args)
    {
        RearrangeArray arrange = new RearrangeArray();
        int arr[] = { 2, 0, 1, 4, 5, 3 };
        int n = arr.length;
 
        System.out.println("Given array is ");
        arrange.printArray(arr, n);
 
        arrange.rearrange(arr, n);
 
        System.out.println("Modified array is ");
        arrange.printArray(arr, n);
    }
}

Python3




# A space efficient Python3 program to
# rearrange contents of arr such that
# arr[j] becomes j if arr[i] is j
 
# A utility function to rearrange elements
# in the cycle starting at arr[i]. This
# function assumes values in arr be from
# 1 to n. It changes arr[j-1] to i+1 if
# arr[i-1] is j+1
def rearrangeUtil(arr, n, i):
     
    # 'val' is the value to be stored at 
    # 'arr[i]'
    # The next value is determined using
    # current index 
    val = -(i + 1)
     
    # The next index is determined using
    # current index
    i = arr[i] - 1
  
    # While all elements in cycle are
    # not processed
    while (arr[i] > 0):
         
        # Store value at index as it is
        # going to be used as next index
        new_i = arr[i] - 1
         
        # Update arr
        arr[i] = val
         
        # Update value and index for
        # next iteration
        val = -(i + 1)
        i = new_i
 
# A space efficient method to rearrange
# 'arr[0..n-1]' so that 'arr[j]' becomes
# 'i' if 'arr[i]' is 'j'
def rearrange(arr, n):
     
    # Increment all values by 1, so that
    # all elements can be made negative to
    # mark them as visited
    for i in range(n):
        arr[i] += 1
         
    # Process all cycles
    for i in range(n):
         
        # Process cycle starting at arr[i] if 
        # this cycle is not already processed
        if (arr[i] > 0):
            rearrangeUtil(arr, n, i)
     
    # Change sign and values of arr to
    # get the original values back, i.e., 
    # values in range from 0 to n-1
    for i in range(n):
        arr[i] = (-arr[i]) - 1
 
# A utility function to prcontents o
# f arr[0..n-1]
def printArray(arr, n):
     
    for i in range(n):
        print(arr[i], end = " ")
    print()
 
# Driver code
arr = [ 2, 0, 1, 4, 5, 3 ]
n = len(arr)
 
print("Given array is ")
printArray(arr, n)
 
rearrange(arr, n)
 
print("Modified array is ")
printArray(arr, n)
 
# This code is contributed by shubhamsingh10

C#




// A simple C# program to
// rearrange contents of arr[]
// such that arr[j] becomes
// j if arr[i] is j
using System;
 
class GFG {
    // A simple method to rearrange
    // 'arr[0..n-1]' so that 'arr[j]'
    // becomes 'i' if 'arr[i]' is 'j'
    void rearrangeNaive(int[] arr,
                        int n)
    {
        // Create an auxiliary
        // array of same size
        int[] temp = new int[n];
        int i;
 
        // Store result in temp[]
        for (i = 0; i < n; i++)
            temp[arr[i]] = i;
 
        // Copy temp back to arr[]
        for (i = 0; i < n; i++)
            arr[i] = temp[i];
    }
 
    // A utility function to
    // print contents of arr[0..n-1]
    void printArray(int[] arr, int n)
    {
        int i;
        for (i = 0; i < n; i++) {
            Console.Write(arr[i] + " ");
        }
        Console.WriteLine("");
    }
 
    // Driver Code
    public static void Main()
    {
        GFG arrange = new GFG();
        int[] arr = { 2, 0, 1, 4, 5, 3 };
        int n = arr.Length;
 
        Console.WriteLine("Given array is ");
        arrange.printArray(arr, n);
 
        arrange.rearrangeNaive(arr, n);
 
        Console.WriteLine("Modified array is ");
        arrange.printArray(arr, n);
    }
}
 
// This code is contributed by anuj_67.

Javascript




<script>
 
// A space efficient Javascript program to rearrange contents of
// arr[] such that arr[j] becomes j if arr[i] is j
 
     
    // A utility function to rearrange elements in the cycle
    // starting at arr[i]. This function assumes values in
    // arr[] be from 1 to n.  It changes arr[j-1] to i+1
    // if arr[i-1] is j+1
    function rearrangeUtil(arr,n,i)
    {
        // 'val' is the value to be stored at 'arr[i]'
  
        // The next value is determined using current index
        let val = -(i + 1);
  
        // The next index is determined
        // using current value
        i = arr[i] - 1;
  
        // While all elements in cycle are not processed
        while (arr[i] > 0) {
            // Store value at index as it is going to be
            // used as next index
            let new_i = arr[i] - 1;
  
            // Update arr[]
            arr[i] = val;
  
            // Update value and index for next iteration
            val = -(i + 1);
            i = new_i;
        }
    }
     
    // A space efficient method to rearrange 'arr[0..n-1]'
    // so that 'arr[j]' becomes 'i' if 'arr[i]' is 'j'
    function rearrange(arr,n)
    {
        // Increment all values by 1, so that all elements
        // can be made negative to mark them as visited
        let i;
        for (i = 0; i < n; i++)
            arr[i]++;
  
        // Process all cycles
        for (i = 0; i < n; i++) {
            // Process cycle starting at arr[i] if this cycle is
            // not already processed
            if (arr[i] > 0)
                rearrangeUtil(arr, n, i);
        }
  
        // Change sign and values of arr[] to get the original
        // values back, i.e., values in range from 0 to n-1
        for (i = 0; i < n; i++)
            arr[i] = (-arr[i]) - 1;
    }
     
    // A utility function to print contents of arr[0..n-1]
    function printArray(arr,n)
    {
        let i;
        for (i = 0; i < n; i++)
            document.write(arr[i] + " ");
        document.write("<br>");
    }
     
    // Driver program
     
    let arr=[2, 0, 1, 4, 5, 3];
    let n = arr.length;
     
    document.write("Given array is <br>");
    printArray(arr, n);
     
    rearrange(arr, n);
    document.write("Modified array is <br>");
    printArray(arr, n);
     
    // This code is contributed by rag2127
     
</script>

Output: 

Given array is
2 0 1 4 5 3
Modified array is
1 2 0 5 3 4 

The time complexity of this method seems to be more than O(n) at first look. If we take a closer look, we can notice that no element is processed more than a constant number of times.
Another Method: The idea is to store each element’s new and old value as quotient and remainder of n, respectively (n being the size of the array). 
For example, Suppose an element’s new value is 2, the old value is 1 and n is 3, then the element’s value is stored as 1 + 2*3 = 7. We can retrieve its old value by 7%3 = 1 and its new value by 7/3 = 2. 
Thanks Prateek Oraon for suggesting this method. 
 

C++




// A simple C++ program to rearrange
// contents of arr[] such that arr[j]
// becomes j if arr[i] is j
#include <bits/stdc++.h>
using namespace std;
 
// A simple method to rearrange
// 'arr[0..n-1]' so that 'arr[j]'
// becomes 'i' if 'arr[i]' is 'j'
void rearrange(int arr[], int n)
{
    for (int i = 0; i < n; i++) {
 
        // retrieving old value and
        // storing with the new one
        arr[arr[i] % n] += i * n;
    }
 
    for (int i = 0; i < n; i++) {
 
        // retrieving new value
        arr[i] /= n;
    }
}
 
// A utility function to print
// contents of arr[0..n-1]
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
 
    cout << endl;
}
 
// Driver program
int main()
{
    int arr[] = { 2, 0, 1, 4, 5, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << "Given array is : " << endl;
    printArray(arr, n);
 
    rearrange(arr, n);
 
    cout << "Modified array is :" << endl;
    printArray(arr, n);
 
    return 0;
}

Java




// A simple JAVA program to rearrange
// contents of arr[] such that arr[j]
// becomes j if arr[i] is j
 
class GFG {
 
    // A simple method to rearrange
    // 'arr[0..n-1]' so that 'arr[j]'
    // becomes 'i' if 'arr[i]' is 'j'
    static void rearrange(int arr[], int n)
    {
        for (int i = 0; i < n; i++) {
 
            // retrieving old value and
            // storing with the new one
            arr[arr[i] % n] += i * n;
        }
 
        for (int i = 0; i < n; i++) {
 
            // retrieving new value
            arr[i] /= n;
        }
    }
 
    // A utility function to print
    // contents of arr[0..n-1]
    static void printArray(int arr[], int n)
    {
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
 
        System.out.println();
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 2, 0, 1, 4, 5, 3 };
        int n = arr.length;
 
        System.out.println("Given array is : ");
        printArray(arr, n);
 
        rearrange(arr, n);
 
        System.out.println("Modified array is :");
        printArray(arr, n);
    }
}
 
// This code has been contributed by 29AjayKumar

Python3




# A simple Python3 program to rearrange
# contents of arr[] such that arr[j]
# becomes j if arr[i] is j
 
# A simple method to rearrange
# 'arr[0..n-1]' so that 'arr[j]'
# becomes 'i' if 'arr[i]' is 'j'
def rearrange(arr, n):
     
    for i in range(n):
         
        # Retrieving old value and
        # storing with the new one
        arr[arr[i] % n] += i * n
     
    for i in range(n):
         
        # Retrieving new value
        arr[i] //= n
     
# A utility function to pr
# contents of arr[0..n-1]
def prArray(arr, n):
     
    for i in range(n):
        print(arr[i], end = " ")
    print()
 
# Driver code
arr = [2, 0, 1, 4, 5, 3]
n = len(arr)
 
print("Given array is : ")
prArray(arr, n)
 
rearrange(arr, n)
 
print("Modified array is :")
prArray(arr, n)
 
# This code is contributed by shubhamsingh10

C#




// A simple C# program to rearrange
// contents of arr[] such that arr[j]
// becomes j if arr[i] is j
using System;
 
class GFG{
 
    // A simple method to rearrange
    // 'arr[0..n-1]' so that 'arr[j]'
    // becomes 'i' if 'arr[i]' is 'j'
    static void rearrange(int[] arr, int n)
    {
        for (int i = 0; i < n; i++) {
     
            // retrieving old value and
            // storing with the new one
            arr[arr[i] % n] += i * n;
        }
     
        for (int i = 0; i < n; i++) {
     
            // retrieving new value
            arr[i] /= n;
        }
    }
     
    // A utility function to print
    // contents of arr[0..n-1]
    static void printArray(int[] arr, int n)
    {
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
     
        Console.WriteLine();
    }
     
    // Driver program
    static public void Main ()
    {
        int[] arr = { 2, 0, 1, 4, 5, 3 };
        int n = arr.Length;
     
        Console.WriteLine("Given array is : ");
        printArray(arr, n);
     
        rearrange(arr, n);
     
        Console.WriteLine("Modified array is :");
        printArray(arr, n);
    }
}
 
// This code is contributed by shubhamsingh10

Javascript




<script>
 
// A simple javascript program to rearrange
// contents of arr such that arr[j]
// becomes j if arr[i] is j
 
 
// A simple method to rearrange
// 'arr[0..n-1]' so that 'arr[j]'
// becomes 'i' if 'arr[i]' is 'j'
function rearrange(arr , n)
{
    for (i = 0; i < n; i++) {
 
        // retrieving old value and
        // storing with the new one
        arr[arr[i] % n] += i * n;
    }
 
    for (i = 0; i < n; i++) {
 
        // retrieving new value
        arr[i] = parseInt(arr[i]/n);
    }
}
 
// A utility function to print
// contents of arr[0..n-1]
function printArray(arr , n)
{
    for (i = 0; i < n; i++) {
        document.write(arr[i] + " ");
    }
 
    document.write();
}
 
// Driver code
var arr = [ 2, 0, 1, 4, 5, 3 ];
var n = arr.length;
 
document.write("Given array is : " + "<br>");
printArray(arr, n);
 
rearrange(arr, n);
document.write("<br>")
 
document.write("Modified array is : " + "<br>");
printArray(arr, n);
 
// This code contributed by Rajput-Ji
 
</script>

Output: 

Given array is : 
2 0 1 4 5 3 
Modified array is :
1 2 0 5 3 4 

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

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :