Rearrange array to make arr[i] = i

Last Updated : 27 Jan, 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] Rearranging Array Elements – O(n²) Time and O(1) Space

The Idea is to place each element i at index i if it exists in the array.
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.
Repeat this process for all indices to obtain the final rearranged array.

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;
}
C
#include <stdio.h>

// Function to transform the array
void modifyArray(int ar[], int n)
{
    int i, j, temp;

    // Iterate over the array
    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n; j++)
        {
            // Check is any ar[j]
            // exists such that
            // ar[j] is equal to i
            if (ar[j] == i) {
                temp = ar[j];
                ar[j] = ar[i];
                ar[i] = temp;
                break;
            }
        }
    }

    // Iterate over array
    for (i = 0; i < n; i++)
    {
        // If not present
        if (ar[i] != i)
        {
            ar[i] = -1;
        }
    }
    // Print the output
  
    for (i = 0; i < n; i++) {
        printf("%d ",ar[i]);
    }
}

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

 
Java
public class GfG{
    
  static void modifyArray(int ar[], int n)
{
    int i, j, temp;
    
    // Iterate over the array
    for(i = 0; i < n; i++)
    {
        for(j = 0; j < n; j++)
        {
            
            // Check is any ar[j]
            // exists such that
            // ar[j] is equal to i
            if (ar[j] == i) 
            {
                temp = ar[j];
                ar[j] = ar[i];
                ar[i] = temp;
                break;
            }
        }
    }
 
    // Iterate over array
    for(i = 0; i < n; i++)
    {
        
        // If not present
        if (ar[i] != i)
        {
            ar[i] = -1;
        }
    }
 
    // Print the output
    
    for(i = 0; i < n; i++) 
    {
        System.out.print(ar[i] + " ");
    }
}

 
public static void main(String[] args)
{
    int n, ar[] = { -1, -1, 6, 1, 9, 
                     3, 2, -1, 4, -1 };
    n = ar.length;
  
    modifyArray(ar, n);
}
}
Python
def modifyArray(ar, n):
    
    # Iterate over the array
    for i in range(n):
        for j in range(n):

            # Check is any ar[j]
            # exists such that
            # ar[j] is equal to i
            if (ar[j] == i):
                ar[j], ar[i] = ar[i], ar[j]

    # Iterate over array
    for i in range(n):
        
        # If not present
        if (ar[i] != i):
            ar[i] = -1

    # Print the output
    
    for i in range(n):
        print(ar[i], end = " ")

 
ar = [ -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 ]
n = len(ar)
 
modifyArray(ar, n);
C#
using System;

class GfG
{
    // Function to transform the array
    static void modifyArray(int[] arr)
    {
        int n = arr.Length;
        int i, j, temp;

        // Iterate over the array
        for (i = 0; i < n; i++){
            for (j = 0; j < n; j++){
                // Check if any ar[j] exists such that ar[j] == i
                if (arr[j] == i){
                    temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                    break;
                }
            }
        }

        // Iterate over array
        for (i = 0; i < n; i++){
            // If not present
            if (arr[i] != i){
                arr[i] = -1;
            }
        }

        // Print the output
        for (i = 0; i < n; i++){
            Console.Write(arr[i] + " ");
        }
    }

    static void Main()
    {
        int[] arr = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
        modifyArray(arr);
    }
}
Javascript
function modifyArray(ar, n) {
  var i, j, temp;

  // Iterate over the array
  for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
      // Check if any ar[j] exists such that ar[j] is equal to i
      if (ar[j] == i) {
        temp = ar[j];
        ar[j] = ar[i];
        ar[i] = temp;
        break;
      }
    }
  }

  // Iterate over array
  for (i = 0; i < n; i++) {
    // If not present
    if (ar[i] != i) {
      ar[i] = -1;
    }
  }

  // Prepare the output string
  var output = "";
  for (i = 0; i < n; i++) {
    output += ar[i] + " ";
  }

  // Print the output
  console.log(output.trim());
}

 
var ar = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1];
var n = ar.length;

 
modifyArray(ar, n);

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

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

  • The Idea is to 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
import java.util.*;

public class Main {
    static int[] modifyArray(int arr[], int n)
    {
        ArrayList<Integer> vec
            = new ArrayList<>(Collections.nCopies(n, -1));
        for (int i = 0; i < n; i++) {
            if (arr[i] != -1) {
                vec.set(arr[i], arr[i]);
            }
        }

        for (int i = 0; i < n; i++) {
            arr[i] = vec.get(i);
        }
        return arr;
    }

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

        // Function Call
        modifyArray(arr, n);

        // Print output
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
}
Python
# Python program for rearranging
# an array such that arr[i] = i.
  
def modifyArray(arr, n):
    vec = [-1]*n
  
    # Traverse the array
    for i in range(0, n):
  
        # If arr[i] is not -1 then arr[i]
        # is at its correct position.
        if (arr[i] != -1):
            vec[arr[i]] = arr[i]
  
    # Copy vec[] to arr[]
    for i in range(0, n):
        arr[i] = vec[i]
    return arr
  
 
arr = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]
n = len(arr)
  
 
modifyArray(arr, n)
  
# Print output
for i in range(0, n):
    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 Rearrangement by 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.

Steps

  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 Program {
    // Method to modify the array
    static void modifyArray(ref 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(ref 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 

How is time complexity O(n)? In every iteration, we either move ahead or move an element to its correct position. So we do at most 2n work.

Comment