Rearrange array to make arr[i] = i

Last Updated : 27 Oct, 2026

Given an array of elements of length n, ranging from 0 to n - 1. All elements may not be present in the array. If the element is not present then there will be -1 present in the array. Rearrange the array such that arr[i] = i and if i is not present, store -1 at that place.

Examples:

Input: arr[] = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]
Output: [-1, 1, 2, 3, 4, -1, 6, -1, -1, 9]
Explanation: In range 0 to 9, all except 0, 5, 7 and 8 are present. Hence, we print -1 instead of them.

Input: arr[] = [0, 1, 2, 3, 4, 5]
Output: [0, 1, 2, 3, 4, 5]
Explanation: In range 0 to 5, all number are present.

Try It Yourself
redirect icon

[Naive Approach] Nested Loops – O(n²) Time and O(1) Space

Repeat the following process for every index i,

  • linearly search the entire array to check whether the value i is present.
  • If found, move i to index i by swapping.
  • If i is not present in the array, assign -1 to index i.
C++
#include <iostream>
#include <vector>
using namespace std;

void modifyArray(vector<int>& arr) {
    int n = arr.size();

    // Move i to arr[i] if present
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (arr[j] == i) {
                swap(arr[i], arr[j]);
                break;
            }
        }
    }

    // Put -1 for places where i is
    // not present
    for (int i = 0; i < n; i++) {
        if (arr[i] != i) {
            arr[i] = -1;
        }
    }
}

 
int main() {
    vector<int> arr = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
    modifyArray(arr);
    for (int i = 0; i < arr.size(); i++) {
        cout << arr[i] << " ";
    }
    return 0;
}
Java
import java.util.Arrays;

class GfG {

    static void modifyArray(int[] arr) {
        int n = arr.length;

        // Move i to arr[i] if present
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (arr[j] == i) {
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                    break;
                }
            }
        }

        // Put -1 for places where i is not present
        for (int i = 0; i < n; i++) {
            if (arr[i] != i) {
                arr[i] = -1;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1};

        modifyArray(arr);

        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
Python
def modifyArray(arr):
    n = len(arr)

    # Move i to arr[i] if present
    for i in range(n):
        for j in range(n):
            if arr[j] == i:
                arr[i], arr[j] = arr[j], arr[i]
                break

    # Put -1 for places where i is not present
    for i in range(n):
        if arr[i] != i:
            arr[i] = -1


if __name__ == "__main__":
    arr = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]

    modifyArray(arr)

    for i in range(len(arr)):
        print(arr[i], end=" ")
C#
using System;

class GFG {

    static void modifyArray(int[] arr) {
        int n = arr.Length;

        // Move i to arr[i] if present
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (arr[j] == i) {
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                    break;
                }
            }
        }

        // Put -1 for places where i is not present
        for (int i = 0; i < n; i++) {
            if (arr[i] != i) {
                arr[i] = -1;
            }
        }
    }

    static void Main() {
        int[] arr = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1};

        modifyArray(arr);

        for (int i = 0; i < arr.Length; i++) {
            Console.Write(arr[i] + " ");
        }
    }
}
Javascript
function modifyArray(arr) {
    let n = arr.length;

    // Move i to arr[i] if present
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            if (arr[j] === i) {
                let temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                break;
            }
        }
    }

    // Put -1 for places where i is not present
    for (let i = 0; i < n; i++) {
        if (arr[i] !== i) {
            arr[i] = -1;
        }
    }
}

// Driver code
let arr = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1];

modifyArray(arr);

for (let i = 0; i < arr.length; i++) {
    process.stdout.write(arr[i] + " ");
}

Output
-1 1 2 3 4 -1 6 -1 -1 9 

[Better Approach] Auxiliary Array - O(n) Time and O(n) Space

  • Create an auxiliary array of size n and initialize all its elements to -1.
  • Traverse the input array, and for each value arr[i] that is not -1, place it at index arr[i] in the auxiliary array.
  • Finally, copy the auxiliary array back into the original array to obtain the rearranged array.
C++
#include <iostream>
#include <vector>
using namespace std;

// Function to rearrange the array such that arr[i] = i.
void modifyArray(vector<int>& arr) {
    int n = arr.size();
    vector<int> temp(n, -1);
    
    for (int i = 0; i < n; i++) {
        if (arr[i] != -1) {
            temp[arr[i]] = arr[i];
        }
    }

    // Update the original array
    for (int i = 0; i < n; i++) {
        arr[i] = temp[i];
    }
}

 
int main() {
    vector<int> arr = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
    modifyArray(arr);
    for (int i = 0; i < arr.size(); i++)
        cout << arr[i] << " ";
    return 0;
}
Java
class GfG {

    // Function to rearrange the array such that arr[i] = i
    static void modifyArray(int[] arr) {
        int n = arr.length;
        int[] temp = new int[n];

        for (int i = 0; i < n; i++) {
            temp[i] = -1;
        }

        for (int i = 0; i < n; i++) {
            if (arr[i] != -1) {
                temp[arr[i]] = arr[i];
            }
        }

        // Update the original array
        for (int i = 0; i < n; i++) {
            arr[i] = temp[i];
        }
    }

    public static void main(String[] args) {
        int[] arr = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1};

        modifyArray(arr);

        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
Python
def modifyArray(arr):
    n = len(arr)
    temp = [-1] * n

    for i in range(n):
        if arr[i] != -1:
            temp[arr[i]] = arr[i]

    # Update the original array
    for i in range(n):
        arr[i] = temp[i]


if __name__ == "__main__":
    arr = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]

    modifyArray(arr)

    for i in range(len(arr)):
        print(arr[i], end=" ")
C#
// C# code addition 
using System;

class GFG
{
    // Function to rearrange an
    // array such that arr[i] = i.
    static int[] modifyArray(int[] arr){
        int n = arr.Length;

        var vec = new int[n];
        for (int i = 0; i < n; i++){
            vec[i] = -1;
        }

        for (int i = 0; i < n; i++){
            if (arr[i] != -1){
                vec[arr[i]] = arr[i];
            }
        }
    
        // Update the original array
        for (int i = 0; i < n; i++){
            arr[i] = vec[i];
        }

        return arr;
    }

    public static void Main(string[] args)
    {
        int[] arr = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };

        modifyArray(arr);

        // Print output
        for (int i = 0; i < arr.Length; i++)
            Console.Write(arr[i] + " ");
    }
}
Javascript
function modifyArray(arr) {
    let n = arr.length;
    let vec = new Array(n).fill(-1);
    
    for (let i = 0; i < n; i++) {
        if (arr[i] !== -1) {
            vec[arr[i]] = arr[i];
        }
    }
    
    for (let i = 0; i < n; i++) {
        arr[i] = vec[i];
    }
    
    return arr;
}
 
let arr = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1];
 
modifyArray(arr);
 
console.log(arr.join(" "));

Output
-1 1 2 3 4 -1 6 -1 -1 9 

[Expected Approach] In-Place Swapping – O(n) Time and O(1) Space

The idea is to rearrange the array in-place by repeatedly swapping elements until each element reaches its correct index, without using any extra space.

Step by Step Approach:

  1. Traverse the array from left to right.
  2. If the current element arr[i] is already at its correct position (arr[i] == i), move to the next index.
  3. If arr[i] is not -1, swap it with the element at index arr[i].
  4. After swapping, do not increment the index, as the new element at arr[i] may still be misplaced.
  5. Repeat the swapping process until either arr[i] becomes -1 or the correct element is placed at index i.
  6. Continue this process for all indices in the array.
C++
#include <iostream>
#include <algorithm> 
#include <vector>
using namespace std;

void modifyArray(vector<int>& arr) {
    int i = 0;
    while (i < arr.size()) {
      
        // Swap if the element arr[i] is not at arr[arr[i]]
        if (arr[i] != -1 && arr[i] != arr[arr[i]]) {
            swap(arr[i], arr[arr[i]]);
          
        } else {
          
            // Increment i if element is at its correct position
            i++;
        }
    }
}

int main() {
    vector<int> arr = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
    modifyArray(arr);
    for (int x : arr)
        cout << x << " ";    
    return 0;
}
C
#include <stdio.h>

void modifyArray(int arr[], int n)
{
    for (int i = 0; i < n;)
    {
        if (arr[i] >= 0 && arr[i] != i)
        {
            int correct = arr[i];

            if (arr[correct] == -1) {
                arr[correct] = correct;
                arr[i] = -1;
                i++;   
            } else {
                int temp = arr[correct];
                arr[correct] = arr[i];
                arr[i] = temp;
            }
        }
        else
        {
            i++;
        }
    }
}


 
int main()
{
    int arr[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
    int n = sizeof(arr) / sizeof(arr[0]);

     
    modifyArray(arr, n);

     
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}
Java
 import java.util.*;

public class Solution {

    // Function to modify the array by swapping elements
      static void modifyArray(int[] arr) {
        int i = 0;
        
        // Iterate through the array
        while (i < arr.length) {
            // Swap if the element arr[i] is not at arr[arr[i]]
            if (arr[i] != -1 && arr[i] != arr[arr[i]]) {
                // Swap the elements arr[i] and arr[arr[i]]
                int temp = arr[i];
                arr[i] = arr[arr[i]];
                arr[temp] = temp;
            } else {
                // Increment i if element is at its correct position
                i++;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
        
        // Call the modifyArray method
        modifyArray(arr);

        // Print the modified array
        for (int x : arr) {
            System.out.print(x + " ");
        }
    }
}
Python
def modifyArray(arr):
    i = 0

    # Iterate through the array
    while i < len(arr):
        # Swap if the element arr[i] is not at arr[arr[i]]
        if arr[i] != -1 and arr[i] != arr[arr[i]]:
            # Swap the elements arr[i] and arr[arr[i]]
            temp = arr[i];
            arr[i]= arr[arr[i]];
            arr[temp]= temp;
             
        else:
            # Increment i if element is at its correct position
            i += 1


# Initialize the array and call the function directly
arr = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]

# Call the modifyArray function
modifyArray(arr)

# Print the modified array
print(" ".join(map(str, arr)))
C#
using System;

class GFG {
    // Method to modify the array
    static void modifyArray(int[] arr)
    {
        int i = 0;

        // Iterate through the array
        while (i < arr.Length) {
            // Swap if the element arr[i] is not at
            // arr[arr[i]]
            if (arr[i] != -1 && arr[i] != arr[arr[i]]) {
                // Swap the elements arr[i] and arr[arr[i]]
                int temp = arr[i];
                arr[i] = arr[arr[i]];
                arr[temp] = temp;
            }
            else {
                // Increment i if element is at its correct
                // position
                i++;
            }
        }
    }

    static void Main()
    {
        // Initialize the array
        int[] arr = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };

        // Call the ModifyArray function
        modifyArray(arr);

        // Print the modified array
        Console.WriteLine(string.Join(" ", arr));
    }
}
Javascript
// Function to modify the array
function modifyArray(arr) {
    let i = 0;

    // Iterate through the array
    while (i < arr.length) {
        // Swap if the element arr[i] is not at arr[arr[i]]
        if (arr[i] !== -1 && arr[i] !== arr[arr[i]]) {
            // Swap the elements arr[i] and arr[arr[i]]
            let temp = arr[i];
            arr[i] = arr[arr[i]];
            arr[temp] = temp;
        } else {
            // Increment i if element is at its correct position
            i++;
        }
    }
}

 
let arr = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1];
modifyArray(arr);
console.log(arr.join(" "));

Output
-1 1 2 3 4 -1 6 -1 -1 9 
Comment