Open In App

Rearrange an array such that arr[i] = i

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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, display -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.

Naive Approach - O(n^2) Time and O(1) Space

First make sure that i is moved to arr[i] if present. For this we run two nested loops. For every arr[i], we linearly search for i. If we find, we move it to index i. Then we put -1 for the places where i is not present.

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
// C program for above approach
#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
// Java program for above approach
public class GfG{
    
// Function to transform the array
  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
# Python3 program for above approach

# Function to transform the array
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#
// C# program for above approach
using System;
class GfG {
    
    // Function to transform the array
    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++) 
        {
            Console.Write(ar[i] + " ");
        }
    }  
    
  static void Main() {
        int[] ar = { -1, -1, 6, 1, 9, 
                     3, 2, -1, 4, -1 };
        int n = ar.Length;
      
         
        modifyArray(ar, n);
  }
}

 
Javascript
// Function to transform the array
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 - O(n) Time and O(n) Space

Follow these steps to rearrange an array

  • Make an auxiliary array temp[] of size n and fill its every element by -1.
  • Now traverse the input array and if any element arr[i] is not equal to -1 then
    • Use arr[i] as an index in temp[] and make temp[arr[i]] = arr[i]
  • In last copy all elements of the vector into the input array and then return or print that input 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)
    {
        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];
            }
        }

        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 };
        int n = arr.Length;

        
        modifyArray(arr, n);

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

// The code is contributed by Arushi Goel. 
Javascript
// JavaScript program for rearrange an
// array such that arr[i] = i.

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 - O(n) Time and O(1) Space

We iterate through every index and if the element is at its correct position, we ignore it. Else if the element is not -1 then we move the current element to its correct position by swapping it with the element at its correct position. Now the current element again might not be at its correct position. So we do not move to the next element and again do swapping. We keep doing it until either we reach -1 or the correct element is placed during swap.

  • Iterate through elements in an array 
  • If arr[i] == i, do nothing and increment i.
  • Else if arr[i] != -1, put arr[i] at arr[arr[i]] ( swap arr[i] with arr[arr[i]]) and do not change i so that the newly moved item is swapped to its position in the next iteration

An alternate implementation can be running a while loop inside the for loop.

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
// C program for rearrange an
// array such that arr[i] = i.
#include <stdio.h>

void modifyArray(int arr[], int n)
{

    for (int i = 0; i < n;) 
    {
        if (arr[i] >= 0 && arr[i] != i)
            arr[arr[i]] = (arr[arr[i]] + arr[i])
                          - (arr[i] = arr[arr[i]]);
        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 


Illustration

arr = { -1, 2, -1, 1, 3 }

i = 0 : arr[i] = -1, ignore it by doing i++
i = 1 : arr[1] = 2, swap(arr[1], arr[2]), arr = { -1, -1, 2, 1, 3 }
i = 1 : arr[1] = -1, ignore it by doing i++
i = 2 : arr[1] = 2, ignore it by doing i++
i = 3. arr[3] = -1, swap(arr[3], arr[1]), arr = { -1, 1, 2, -1, 3 }
i = 3. arr[3] = -1, ignore it by doing i++
i = 4. arr[4] = 3, swap(arr[4], arr[3]), arr = { -1, 1, 2, 3, -1 }
i = 4, arr[4] = -1. ignore it by doing i++

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.


Next Article
Article Tags :
Practice Tags :

Similar Reads