Modify an array such that if 'arr[i]' is 'j' then arr[j] becomes i

Last Updated : 29 Mar, 2025

Given an array arr[] of size n, where all elements are distinct and fall within the range 0 to n-1. The task is to modify arr[] such that if arr[i] = j, then it gets transformed into arr[j] = i.

Examples: 

Input: arr[] = [1, 3, 0, 2]
Output: 2 0 3 1
Explanation: Since arr[0] = 1, update arr[1] to 0
Since arr[1] = 3, update arr[3] to 1
Since arr[2] = 0, update arr[0] to 2
Since arr[3] = 2, update arr[2] to 3

Input: arr[] = [2, 0, 1, 4, 5, 3]
Output: 1 2 0 5 3 4
Explanation: Since arr[0] = 2, update arr[2] to 0
Since arr[1] = 0, update arr[0] to 1
Since arr[2] = 1, update arr[1] to 2
Since arr[3] = 4, update arr[4] to 3
Since arr[4] = 5, update arr[5] to 4
Since arr[5] = 3, update arr[3] to 5

Input: arr[] = [3, 2, 1, 0]
Output: 3 2 1 0
Explanation: Since each element is already at its correct index, the array remains unchanged.

[Brute Force Approach] Using an Extra Array - O(n) Time and O(n) Space

The idea is to use an extra array to directly place each element at its correct index without modifying the input during traversal. By observing that each element arr[i] represents its future index, we create a newArr where newArr[arr[i]] = i. Finally, we copy newArr back to arr to complete the rearrangement efficiently.

C++
// C++ Code to Rearrange Array Elements
// using an Extra Array 
#include <bits/stdc++.h>
using namespace std;

void rearrange(vector<int>& arr) {

    int n = arr.size();
    
    // Create an auxiliary array to
    // store new values
    vector<int> newArr(n);

    // Place each element at its correct index
    for (int i = 0; i < n; i++) {  
        newArr[arr[i]] = i;
    }

    // Copy modified values back to the 
    // original array
    for (int i = 0; i < n; i++) {  
        arr[i] = newArr[i];
    }
}


int main() {

    vector<int> arr = {2, 0, 1, 4, 5, 3};

    rearrange(arr); 
    
    for (int x : arr) {  
        cout << x << " ";
    }
    
    return 0;
}
Java
public class Main {
    public static void rearrange(int[] arr) {
        int n = arr.length;
        
        // Create an auxiliary array to store new values
        int[] newArr = new int[n];
        
        // Place each element at its correct index
        for (int i = 0; i < n; i++) {
            newArr[arr[i]] = i;
        }
        
        // Copy modified values back to the original array
        for (int i = 0; i < n; i++) {
            arr[i] = newArr[i];
        }
    }

    public static void main(String[] args) {
        int[] arr = {2, 0, 1, 4, 5, 3};
        rearrange(arr);
        System.out.println(java.util.Arrays.toString(arr));
    }
}
Python
# Rearrange Array Elements using an Extra Array
def rearrange(arr):
    n = len(arr)
    
    # Create an auxiliary array to store new values
    newArr = [0] * n
    
    # Place each element at its correct index
    for i in range(n):
        newArr[arr[i]] = i
        
    # Copy modified values back to the original array
    for i in range(n):
        arr[i] = newArr[i]

arr = [2, 0, 1, 4, 5, 3]
rearrange(arr)
print(arr)
C#
using System;

class Program {
    static void Rearrange(int[] arr) {
        int n = arr.Length;
        
        // Create an auxiliary array to store new values
        int[] newArr = new int[n];
        
        // Place each element at its correct index
        for (int i = 0; i < n; i++) {
            newArr[arr[i]] = i;
        }
        
        // Copy modified values back to the original array
        for (int i = 0; i < n; i++) {
            arr[i] = newArr[i];
        }
    }

    static void Main() {
        int[] arr = {2, 0, 1, 4, 5, 3};
        Rearrange(arr);
        Console.WriteLine(string.Join(", ", arr));
    }
}
JavaScript
// Rearrange Array Elements using an Extra Array
function rearrange(arr) {
    const n = arr.length;
    
    // Create an auxiliary array to store new values
    const newArr = new Array(n);
    
    // Place each element at its correct index
    for (let i = 0; i < n; i++) {
        newArr[arr[i]] = i;
    }
    
    // Copy modified values back to the original array
    for (let i = 0; i < n; i++) {
        arr[i] = newArr[i];
    }
}

const arr = [2, 0, 1, 4, 5, 3];
rearrange(arr);
console.log(arr);

Output
1 2 0 5 3 4 

[Expected Approach 1] Using Cycle Replacement - O(n) Time and O(1) Space

The idea is to transform in the form of cycles. For example, there are two cycles in {2, 0, 1, 4, 5, 3}. One cycle is (2, 0, 1) and other cycle is (4, 5, 3). 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. 

Steps to implement the above idea:

  • Increment all elements by 1 to handle 0-based indexing, ensuring all values are positive for correct cycle detection.
  • Iterate through arr[] and call rearrangeUtil for each unprocessed cycle to reorder elements using negative marking.
  • In rearrangeUtil, traverse the cycle, replacing elements with negative indices while tracking the next index to process.
  • Use arr[i] - 1 to fetch the correct index and maintain the cycle transformation without breaking the sequence.
  • Continue processing cycles until all elements are rearranged, ensuring each value gets placed at its correct position.
  • Iterate again over arr to restore original values by converting negative indices back to their correct 0-based range.
C++
// C++ Code to Rearrange Array Elements
// using Cycle Replacement
#include <bits/stdc++.h>
using namespace std;

// Rearrange elements in a cycle 
// starting at arr[i]
void rearrangeUtil(vector<int>& arr,int i) {
      
    int n = arr.size();
    
    // Store the index
    int val = -(i + 1);

    i = arr[i] - 1;

    while (arr[i] > 0) {

        int next = arr[i] - 1;

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

        // Update value for next cycle
        val = -(i + 1);

        i = next;
    }
}

// Rearrange arr[] so that arr[j] 
// becomes i if arr[i] is j
void rearrange(vector<int>& arr) {

    int n = arr.size();

    // Increment all values
    for (int i = 0; i < n; i++) {  
        arr[i]++;
    }

    // Process cycle
    for (int i = 0; i < n; i++) {

        if (arr[i] > 0) {  
            rearrangeUtil(arr, i);
        }
    }

    // Restore original range
    for (int i = 0; i < n; i++) {  
        arr[i] = (-arr[i]) - 1;
    }
}

void printArray(vector<int>& arr) {

    for (int num : arr) {  
        cout << num << " ";
    }
    cout << endl;
}

int main() {

    vector<int> arr = {2, 0, 1, 4, 5, 3};

    rearrange(arr); 
    
    printArray(arr);   

    return 0;
}
Java
// Java Code to Rearrange Array Elements
// using Cycle Replacement
import java.util.*;

class GfG {

    // Rearrange elements in a cycle 
    // starting at arr[i]
    static void rearrangeUtil(int[] arr, int i) {
        
        int n = arr.length;
        
        // Store the index
        int val = -(i + 1);

        i = arr[i] - 1;

        while (arr[i] > 0) {

            int next = arr[i] - 1;

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

            // Update value for next cycle
            val = -(i + 1);

            i = next;
        }
    }

    // Rearrange arr[] so that arr[j] 
    // becomes i if arr[i] is j
    static void rearrange(int[] arr) {

        int n = arr.length;

        // Increment all values
        for (int i = 0; i < n; i++) {  
            arr[i]++;
        }

        // Process cycle
        for (int i = 0; i < n; i++) {

            if (arr[i] > 0) {  
                rearrangeUtil(arr, i);
            }
        }

        // Restore original range
        for (int i = 0; i < n; i++) {  
            arr[i] = (-arr[i]) - 1;
        }
    }

    static void printArray(int[] arr) {

        for (int num : arr) {  
            System.out.print(num + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {

        int[] arr = {2, 0, 1, 4, 5, 3};

        rearrange(arr); 
        
        printArray(arr);   
    }
}
Python
# Python Code to Rearrange Array Elements
# using Cycle Replacement

# Rearrange elements in a cycle 
# starting at arr[i]
def rearrangeUtil(arr, i):
    
    n = len(arr)
    
    # Store the index
    val = -(i + 1)

    i = arr[i] - 1

    while arr[i] > 0:

        next = arr[i] - 1

        # Update current index
        arr[i] = val

        # Update value for next cycle
        val = -(i + 1)

        i = next

# Rearrange arr[] so that arr[j] 
# becomes i if arr[i] is j
def rearrange(arr):

    n = len(arr)

    # Increment all values
    for i in range(n):  
        arr[i] += 1

    # Process cycle
    for i in range(n):

        if arr[i] > 0:  
            rearrangeUtil(arr, i)

    # Restore original range
    for i in range(n):  
        arr[i] = (-arr[i]) - 1

def printArray(arr):

    for num in arr:  
        print(num, end=" ")
    print()

if __name__ == "__main__":

    arr = [2, 0, 1, 4, 5, 3]

    rearrange(arr) 
    
    printArray(arr)
C#
// C# Code to Rearrange Array Elements
// using Cycle Replacement
using System;

class GfG {

    // Rearrange elements in a cycle 
    // starting at arr[i]
    static void rearrangeUtil(int[] arr, int i) {
        
        int n = arr.Length;
        
        // Store the index
        int val = -(i + 1);

        i = arr[i] - 1;

        while (arr[i] > 0) {

            int next = arr[i] - 1;

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

            // Update value for next cycle
            val = -(i + 1);

            i = next;
        }
    }

    // Rearrange arr[] so that arr[j] 
    // becomes i if arr[i] is j
    static void rearrange(int[] arr) {

        int n = arr.Length;

        // Increment all values
        for (int i = 0; i < n; i++) {  
            arr[i]++;
        }

        // Process cycle
        for (int i = 0; i < n; i++) {

            if (arr[i] > 0) {  
                rearrangeUtil(arr, i);
            }
        }

        // Restore original range
        for (int i = 0; i < n; i++) {  
            arr[i] = (-arr[i]) - 1;
        }
    }

    static void printArray(int[] arr) {

        foreach (int num in arr) {  
            Console.Write(num + " ");
        }
        Console.WriteLine();
    }

    public static void Main() {

        int[] arr = {2, 0, 1, 4, 5, 3};

        rearrange(arr); 
        
        printArray(arr);   
    }
}
JavaScript
// JavaScript Code to Rearrange Array Elements
// using Cycle Replacement

// Rearrange elements in a cycle 
// starting at arr[i]
function rearrangeUtil(arr, i) {
    
    let n = arr.length;
    
    // Store the index
    let val = -(i + 1);

    i = arr[i] - 1;

    while (arr[i] > 0) {

        let next = arr[i] - 1;

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

        // Update value for next cycle
        val = -(i + 1);

        i = next;
    }
}

// Rearrange arr[] so that arr[j] 
// becomes i if arr[i] is j
function rearrange(arr) {

    let n = arr.length;

    // Increment all values
    for (let i = 0; i < n; i++) {  
        arr[i]++;
    }

    // Process cycle
    for (let i = 0; i < n; i++) {

        if (arr[i] > 0) {  
            rearrangeUtil(arr, i);
        }
    }

    // Restore original range
    for (let i = 0; i < n; i++) {  
        arr[i] = (-arr[i]) - 1;
    }
}

function printArray(arr) {

    console.log(arr.join(" "));
}

// Driver Code
let arr = [2, 0, 1, 4, 5, 3];

rearrange(arr); 

printArray(arr);

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

[Expected Approach 2] Using Modulo - O(n) Time and O(1) Space

The idea is to store both the old and new values within the same array using modulo and multiplication. Each element is updated such that arr[arr[i] % n] accumulates the new position while preserving the original value. After processing, the new values are extracted by performing integer division with n. This ensures an in-place transformation without using extra space.

C++
// C++ Code to Rearrange Array Elements
// using modulo
#include <bits/stdc++.h>
using namespace std;

// Rearrange arr[] so that arr[j] 
// becomes i if arr[i] is j
void rearrange(vector<int>& arr) {

    int n = arr.size();

    // Store new values using modulo
    for (int i = 0; i < n; i++) {  
        arr[arr[i] % n] += i * n;
    }

    // Extract new values
    for (int i = 0; i < n; i++) {  
        arr[i] /= n;
    }
}

int main() {

    vector<int> arr = {2, 0, 1, 4, 5, 3};

    rearrange(arr); 
    
    for (int x : arr) {  
        cout << x << " ";
    }

    return 0;
}
Java
// Java Code to Rearrange Array Elements
import java.util.Arrays;

public class Main {

    // Rearrange arr[] so that arr[j] becomes i if arr[i] is j
    public static void rearrange(int[] arr) {

        int n = arr.length;

        // Store new values using modulo
        for (int i = 0; i < n; i++) {
            arr[arr[i] % n] += i * n;
        }

        // Extract new values
        for (int i = 0; i < n; i++) {
            arr[i] /= n;
        }
    }

    public static void main(String[] args) {

        int[] arr = {2, 0, 1, 4, 5, 3};

        rearrange(arr);

        System.out.println(Arrays.toString(arr));
    }
}
Python
# Rearrange arr[] so that arr[j] 
# becomes i if arr[i] is j
def rearrange(arr):
    n = len(arr)
    
    # Store new values using modulo
    for i in range(n):
        arr[arr[i] % n] += i * n
        
    # Extract new values
    for i in range(n):
        arr[i] //= n

if __name__ == '__main__':
    arr = [2, 0, 1, 4, 5, 3]
    rearrange(arr)
    print(' '.join(map(str, arr)))
C#
// C# Code to Rearrange Array Elements
using System;
using System.Linq;

class Program {

    // Rearrange arr[] so that arr[j] becomes i if arr[i] is j
    static void Rearrange(int[] arr) {

        int n = arr.Length;

        // Store new values using modulo
        for (int i = 0; i < n; i++) {
            arr[arr[i] % n] += i * n;
        }

        // Extract new values
        for (int i = 0; i < n; i++) {
            arr[i] /= n;
        }
    }

    static void Main() {

        int[] arr = {2, 0, 1, 4, 5, 3};

        Rearrange(arr);

        Console.WriteLine(string.Join(" ", arr));
    }
}
JavaScript
// Rearrange arr[] so that arr[j] 
// becomes i if arr[i] is j
function rearrange(arr) {
    let n = arr.length;
    
    // Store new values using modulo
    for (let i = 0; i < n; i++) {
        arr[arr[i] % n] += i * n;
    }
    
    // Extract new values
    for (let i = 0; i < n; i++) {
        arr[i] = Math.floor(arr[i] / n);
    }
}

let arr = [2, 0, 1, 4, 5, 3];
rearrange(arr);
console.log(arr.join(' '));

Output
1 2 0 5 3 4 
Comment