The Wayback Machine - https://web.archive.org/web/20241006142734/https://www.geeksforgeeks.org/rearrange-array-arri/
Open In App

Rearrange an array such that arr[i] = i

Last Updated : 20 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Easy
48.65%
9K

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 A[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]

Input : arr = {19, 7, 0, 3, 18, 15, 12, 6, 1, 8,
11, 10, 9, 5, 13, 16, 2, 14, 17, 4}
Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19]

Approach(Naive Approach):

  1. Nav­i­gate the numbers from 0 to n-1.
  2. Now navigate through array.
  3. If (i==a[j]) , then replace the element at i position with a[j] position.
  4. If there is any element in which -1 is used instead of the number then it will be replaced automatically.
  5. Now, iterate through the array and check if (a[i]!=i) , if it s true then replace a[i] with -1.

Below is the implementation for the above approach:  

C++
// C++ program for above approach
#include <iostream>
using namespace std;

// Function to transform the array
void fixArray(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
    cout << "Array after Rearranging" << endl;
    for (i = 0; i < n; i++) {
        cout << ar[i] << " ";
    }
}

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

    // Function Call
    fixArray(ar, n);
}

// Code BY Tanmay Anand
C
// C program for above approach
#include <stdio.h>

// Function to transform the array
void fixArray(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
    printf("Array after Rearranging\n");
    for (i = 0; i < n; i++) {
        printf("%d ",ar[i]);
    }
}

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

    // Function Call
    fixArray(ar, n);
}

// This code is contributed by kothvvsaakash.
Java
// Java program for above approach
public class GFG{
    
// Function to transform the array
public static void fixArray(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
    System.out.println("Array after Rearranging");
    for(i = 0; i < n; i++) 
    {
        System.out.print(ar[i] + " ");
    }
}

// Driver Code
public static void main(String[] args)
{
    int n, ar[] = { -1, -1, 6, 1, 9, 
                     3, 2, -1, 4, -1 };
    n = ar.length;
 
    // Function Call
    fixArray(ar, n);
}
}
Python
# Python3 program for above approach

# Function to transform the array
def fixArray(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
    print("Array after Rearranging")

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

# Driver Code
ar = [ -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 ]
n = len(ar)

# Function Call
fixArray(ar, n);
C#
// C# program for above approach
using System;
class GFG {
    
    // Function to transform the array
    static void fixArray(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
        Console.WriteLine("Array after Rearranging");
        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;
      
        // Function Call
        fixArray(ar, n);
  }
}

// This code is contributed by divyeshrabadiya07
Javascript
// Function to transform the array
function fixArray(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 = "Array after Rearranging\n";
  for (i = 0; i < n; i++) {
    output += ar[i] + " ";
  }

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

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

// Function Call
fixArray(ar, n);


// This code is contributed by ravi18131
PHP
<?php

// Function to transform the array
function fixArray(&$arr, $n) {
    // Iterate over the array
    for ($i = 0; $i < $n; $i++) {
        for ($j = 0; $j < $n; $j++) {
            // Check if any arr[j] exists such that arr[j] is equal to 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;
        }
    }

    // Prepare the output string
    $output = "Array after Rearranging\n";
    for ($i = 0; $i < $n; $i++) {
        $output .= $arr[$i] . " ";
    }

    // Print the output
    echo trim($output) . "\n";
}

// Driver Code
$arr = array(-1, -1, 6, 1, 9, 3, 2, -1, 4, -1);
$n = count($arr);

// Function Call
fixArray($arr, $n);

// This code is contributed by ravi18131
?>

Output
Array after Rearranging
-1 1 2 3 4 -1 6 -1 -1 9 

Time Complexity: O(n2)
Auxiliary Space: O(1), since no extra space has been taken.

Another Approach: 
1. Nav­i­gate through the array. 
2. Check if a[i] = -1, if yes then ignore it. 
3. If a[i] != -1, Check if element a[i] is at its cor­rect posi­tion (i=A[i]). If yes then ignore it. 
4. If a[i] != -1 and ele­ment a[i] is not at its cor­rect posi­tion (i!=A[i]) then place it to its correct posi­tion, but there are two conditions:  

  • Either A[i] is vacate, means A[i] = -1, then just put A[i] = i .
  • OR A[i] is not vacate, means A[i] = x, then int y=x put A[i] = i. Now, we need to place y to its cor­rect place, so repeat from step 3.

Below is the implementation for the above approach: 

C++
// C++ program for rearrange an
// array such that arr[i] = i.
#include <bits/stdc++.h>

using namespace std;

// Function to rearrange an array
// such that arr[i] = i.
void fixArray(int A[], int len)
{
    for (int i = 0; i < len; i++)
    {
        if (A[i] != -1 && A[i] != i)
        {
            int x = A[i];

            // check if desired place
            // is not vacate
            while (A[x] != -1 && A[x] != x) 
            {
                // store the value from
                // desired place
                int y = A[x];

                // place the x to its correct
                // position
                A[x] = x;

                // now y will become x, now
                // search the place for x
                x = y;
            }

            // place the x to its correct
            // position
            A[x] = x;

            // check if while loop hasn't
            // set the correct value at A[i]
            if (A[i] != i)
            {
                // if not then put -1 at
                // the vacated place
                A[i] = -1;
            }
        }
    }
}

// Driver code
int main()
{
    int A[] = { -1, -1, 6, 1, 9, 
               3, 2, -1, 4, -1 };

    int len = sizeof(A) / sizeof(A[0]);

    // Function Call
    fixArray(A, len);

    // Print the output
    for (int i = 0; i < len; i++)
        cout << A[i] << " ";
}

// This code is contributed by Smitha Dinesh Semwal
C
// C program for rearrange an
// array such that arr[i] = i.
#include <stdio.h>

// Function to rearrange an array
// such that arr[i] = i.
void fixArray(int A[], int len)
{
    for (int i = 0; i < len; i++)
    {
        if (A[i] != -1 && A[i] != i)
        {
            int x = A[i];

            // check if desired place
            // is not vacate
            while (A[x] != -1 && A[x] != x) 
            {
                // store the value from
                // desired place
                int y = A[x];

                // place the x to its correct
                // position
                A[x] = x;

                // now y will become x, now
                // search the place for x
                x = y;
            }

            // place the x to its correct
            // position
            A[x] = x;

            // check if while loop hasn't
            // set the correct value at A[i]
            if (A[i] != i)
            {
                // if not then put -1 at
                // the vacated place
                A[i] = -1;
            }
        }
    }
}

// Driver code
int main()
{
    int A[] = { -1, -1, 6, 1, 9, 
               3, 2, -1, 4, -1 };

    int len = sizeof(A) / sizeof(A[0]);

    // Function Call
    fixArray(A, len);

    // Print the output
    for (int i = 0; i < len; i++)
        printf("%d ",A[i]);
}

// This code is contributed by kothavvsaakash
Java
// Java program for rearrange an
// array such that arr[i] = i.
import java.util.*;
import java.lang.*;

public class GfG {

    // Function to rearrange an array
    // such that arr[i] = i.
    public static int[] fix(int[] A)
    {
        for (int i = 0; i < A.length; i++)
        {
            if (A[i] != -1 && A[i] != i) 
            {
                int x = A[i];

                // check if desired place
                // is not vacate
                while (A[x] != -1 && A[x] != x)
                {
                    // store the value from
                    // desired place
                    int y = A[x];

                    // place the x to its correct
                    // position
                    A[x] = x;

                    // now y will become x, now
                    // search the place for x
                    x = y;
                }

                // place the x to its correct
                // position
                A[x] = x;

                // check if while loop hasn't
                // set the correct value at A[i]
                if (A[i] != i) 
                {
                    // if not then put -1 at
                    // the vacated place
                    A[i] = -1;
                }
            }
        }
        return A;
    }

    // Driver code
    public static void main(String[] args)
    {
        int A[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
        System.out.println(Arrays.toString(fix(A)));
    }
}
Python
# Python3 program for rearrange an
# array such that arr[i] = i.

# Function to rearrange an array
# such that arr[i] = i.


def fix(A, len):

    for i in range(0, len):

        if (A[i] != -1 and A[i] != i):
            x = A[i]

            # check if desired place
            # is not vacate
            while (A[x] != -1 and A[x] != x):
                
                # store the value from
                # desired place
                y = A[x]

                # place the x to its correct
                # position
                A[x] = x

                # now y will become x, now
                # search the place for x
                x = y

            # place the x to its correct
            # position
            A[x] = x

            # check if while loop hasn't
            # set the correct value at A[i]
            if (A[i] != i):

                # if not then put -1 at
                # the vacated place
                A[i] = -1


# Driver code
A = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]

fix(A, len(A))

for i in range(0, len(A)):
    print(A[i], end=' ')

# This code is contributed by Saloni1297
C#
// C# program for rearrange
// an array such that
// arr[i] = i.
using System;

class GfG {
    // Function to rearrange an
    // array such that arr[i] = i.
    public static int[] fix(int[] A)
    {
        for (int i = 0; i < A.Length; i++) 
        {
            if (A[i] != -1 && A[i] != i) 
            {
                int x = A[i];

                // check if desired
                // place is not vacate
                while (A[x] != -1 && A[x] != x) 
                {
                    // store the value
                    // from desired place
                    int y = A[x];

                    // place the x to its
                    // correct position
                    A[x] = x;

                    // now y will become x,
                    // now search the place
                    // for x
                    x = y;
                }

                // place the x to its
                // correct position
                A[x] = x;

                // check if while loop
                // hasn't set the correct
                // value at A[i]
                if (A[i] != i) 
                {
                    // if not then put -1
                    // at the vacated place
                    A[i] = -1;
                }
            }
        }
        return A;
    }

    // Driver Code
    static void Main()
    {
        int[] A = new int[] { -1, -1, 6,  1, 9,
                              3,  2,  -1, 4, -1 };
        Console.WriteLine(string.Join(",", fix(A)));
    }
}

// This code is contributed by
// Manish Shaw(manishshaw1)
Javascript
// Function to rearrange an array such that arr[i] = i
function fixArray(A, len) {
    for (let i = 0; i < len; i++) {
        if (A[i] != -1 && A[i] != i) {
            let x = A[i];

            // check if desired place is not vacate
            while (A[x] != -1 && A[x] != x) {
                // store the value from desired place
                let y = A[x];

                // place the x to its correct position
                A[x] = x;

                // now y will become x, now search the place for x
                x = y;
            }

            // place the x to its correct position
            A[x] = x;

            // check if while loop hasn't set the correct value at A[i]
            if (A[i] != i) {
                // if not then put -1 at the vacated place
                A[i] = -1;
            }
        }
    }
}

// Driver Code
let A = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1];
let len = A.length;
fixArray(A, len);

// Prepare the output string
let output = A.join(" ");

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

// This code is contributed by ravi18131
PHP
<?php
// PHP program for rearrange an
// array such that arr[i] = i.

// Function to rearrange an 
// array such that arr[i] = i.
function fix(&$A, $len)
{
    for ($i = 0; $i < $len; $i++) 
    {
        if ($A[$i] != -1 && 
            $A[$i] != $i) 
        {
            $x = $A[$i];

            // check if desired 
            // place is not vacate
            while ($A[$x] != -1 && 
                   $A[$x] != $x)
            {
                // store the value 
                // from desired place
                $y = $A[$x];

                // place the x to its 
                // correct position
                $A[$x] = $x;

                // now y will become x, 
                // now search the place 
                // for x
                $x = $y;
            }

            // place the x to its 
            // correct position
            $A[$x] = $x;

            // check if while loop hasn't
            // set the correct value at A[i]
            if ($A[$i] != $i) 
            {
                // if not then put -1 
                // at the vacated place
                $A[$i] = -1;
            }
        }
    }
}

// Driver Code
$A = array(-1, -1, 6, 1, 9,
            3, 2, -1, 4, -1);

$len = count($A);
fix($A, $len);

for ($i = 0; $i < $len; $i++)
    echo ($A[$i]." ");
    
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

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

Time Complexity: O(n)
Auxiliary Space: O(1)

Another Approach (Using Set) : 
1) Store all the numbers present in the array into a Set 
2) Iterate through the length of the array, if the corresponding position element is present in the Set, then set A[i] = i, else A[i] = -1

Below is the implementation of the above approach. 

C++
#include <iostream>
#include <unordered_set>

using namespace std;

void fixArray(int arr[], int n)
{
  // a set
  unordered_set<int> s;
  
  // Enter each element which is not -1 in set
  for(int i=0; i<n; i++)
  {
    if(arr[i] != -1)
      s.insert(arr[i]);
  }
  
  // Navigate through array,
  // and put A[i] = i,
  // if i is present in set
  for(int i=0; i<n; i++)
  {
    // if i(index) is found in hmap
    if(s.find(i) != s.end())
    {
      arr[i] = i;
    }
    // if i is not found
    else
    {
      arr[i] = -1;
    }
  }
  
}

// Driver Code
int main() {
  
  // Array initialization
  int arr[] {-1, -1, 6, 1, 9,
          3, 2, -1, 4,-1};
  int n = sizeof(arr) / sizeof(arr[0]);
  
  // Function Call
  fixArray(arr, n);
  
  // Print output
  for(int i=0; i<n; i++)
    cout << arr[i] << ' ';
  
  return 0;
}

// this code is contributed by dev chaudhary
Java
// Java program for rearrange an 
// array such that arr[i] = i.
import java.util.*;
import java.lang.*;

class GfG {

    // Function to rearrange an array
    // such that arr[i] = i.
    public static int[] fix(int[] A)
    {
        Set<Integer> s = new HashSet<Integer>();

        // Storing all the values in the HashSet
        for(int i = 0; i < A.length; i++)
        {
           s.add(A[i]);
        }

        for(int i = 0; i < A.length; i++)
        {
           if(s.contains(i))
             A[i] = i;
           else
             A[i] = -1;
        }

      return A;
}

    // Driver code
    public static void main(String[] args)
    {
        int A[] = {-1, -1, 6, 1, 9,
                    3, 2, -1, 4,-1};
                    
        // Function calling
        System.out.println(Arrays.toString(fix(A)));
    }
}
Python
# Python3 program for rearrange an 
# array such that arr[i] = i.

# Function to rearrange an array
# such that arr[i] = i.
def fix(A):
    s = set()
    
    # Storing all the values in the Set
    for i in range(len(A)):
        s.add(A[i])

    for i in range(len(A)):
      
        # check for item if present in set
        if i in s:
            A[i] = i
        else:
            A[i] = -1
    return A
    
# Driver code
if __name__ == "__main__":
    A = [-1, -1, 6, 1, 9,
          3, 2, -1, 4,-1]
    print(fix(A))

# This code is contributed by Chitranayal
C#
using System;
using System.Collections.Generic;
public class main{
    static void fix(int[] a,int n){
       HashSet<int> hs=new HashSet<int>();
        
        // Traverse the array
        // and add each element
        // to the HashSet
        for(int i=0;i<n;i++)
        hs.Add(a[i]);
        
        // Again traverse from i=0 -> i=n-1
        for(int i=0;i<n;i++)
        {
            // If HashSet contains i
            // Then make a[i]=i,
            // else a[i]=-1
            if(hs.Contains(i))
            a[i]=i;
            else
            a[i]=-1;
        }
    }
    static public void Main (){
        int[] arr={-1, -1, 6, 1, 9, 
                             3, 2, -1, 4,-1};
        int n=arr.Length;
        fix(arr,n);
        
        for(int i=0;i<n;i++) 
        Console.Write(arr[i]+" ");
        
        Console.WriteLine();
    }
}
Javascript
// Function to rearrange an array such that arr[i] = i
function fixArray(A) {
    let s = new Set();

    // Storing all the values in the Set
    for (let i = 0; i < A.length; i++) {
        if (A[i] != -1) {
            s.add(A[i]);
        }
    }

    // Rearranging the array
    for (let i = 0; i < A.length; i++) {
        if (s.has(i)) {
            A[i] = i;
        } else {
            A[i] = -1;
        }
    }

    return A;
}

// Driver Code
let A = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1];

// Function call
let ans = fixArray(A);

// Prepare the output string
let output = ans.join(" ");

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

// This code is contributed by ravi18131
PHP
<?php

// Function to rearrange an array such that arr[i] = i
function fixArray($arr) {
    $set = [];

    // Storing all the values in the Set
    foreach ($arr as $value) {
        if ($value != -1) {
            $set[$value] = true;
        }
    }

    // Rearranging the array
    for ($i = 0; $i < count($arr); $i++) {
        if (isset($set[$i])) {
            $arr[$i] = $i;
        } else {
            $arr[$i] = -1;
        }
    }

    return $arr;
}

// Driver Code
$arr = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1];

// Function call
$ans = fixArray($arr);

// Prepare the output string
$output = implode(" ", $ans);

// Print the output
echo $output . "\n";

// This code is contributed by ravi18131

?>

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

Time Complexity: O(n)
Auxiliary Space: O(n)

Another Approach (Swap elements in Array) : Using cyclic sort
1) Iterate through elements in an array 
2) If arr[i] >= 0 && arr[i] != i, put arr[i] at i ( swap arr[i] with arr[arr[i]])

Below is the implementation of the above approach. 

C++
// C++ program for rearrange an
// array such that arr[i] = i.
#include <iostream>
#include <algorithm> // for swap
using namespace std;

void fixArray(int arr[], int n)
{
    int i = 0;
    while (i < n) {
        int correct = arr[i];
        if (arr[i] != -1 && arr[i] != arr[correct]) {
          // if array element should be lesser than
          // size and array element should not be at
          // its correct position then only swap with
          // its correct position or index value
            swap(arr[i], arr[correct]);
        }
        else {
          // if element is at its correct position
          // just increment i and check for remaining
          // array elements
            i++;
        }
    }
}

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

    // Function Call
    fixArray(arr, n);

    // Print output
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    return 0;
}

// This Code is Contributed by ravi18131
C
// C program for rearrange an
// array such that arr[i] = i.
#include <stdio.h>

void fixArray(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++;
    }
}

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

    // Function Call
    fixArray(arr, n);

    // Print output
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}

// This Code is Contributed by Adarsh_Verma
Java
// Java program for rearrange an
// array such that arr[i] = i.
import java.util.Arrays;

class Program 
{
    public static void main(String[] args)
    {
        int[] arr = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
        for (int i = 0; i < arr.length;)
        {
            if (arr[i] >= 0 && arr[i] != i) 
            {
                int ele = arr[arr[i]];
                arr[arr[i]] = arr[i];
                arr[i] = ele;
            }
            else 
            {
                i++;
            }
        }
        System.out.println(Arrays.toString(arr));
    }
}

/* This Java code is contributed by PrinciRaj1992*/
Python
# Python3 program for rearrange an
# array such that arr[i] = i.
if __name__ == "__main__":

    arr = [-1, -1, 6, 1, 9,
           3, 2, -1, 4, -1]
    n = len(arr)
    i = 0
    while i < n:

        if (arr[i] >= 0 and arr[i] != i):
            (arr[arr[i]],
             arr[i]) = (arr[i],
                        arr[arr[i]])
        else:
            i += 1

    for i in range(n):
        print(arr[i], end=" ")

# This code is contributed by Chitranayal
C#
// C# program for rearrange an
// array such that arr[i] = i.
using System;

namespace GFG {

class Program {
    static void Main(string[] args)
    {
        int[] arr = { -1, -1, 6, 1, 9, 
                     3, 2, -1, 4, -1 };
        for (int i = 0; i < arr.Length;)
        {
            if (arr[i] >= 0 && arr[i] != i) 
            {
                int ele = arr[arr[i]];
                arr[arr[i]] = arr[i];
                arr[i] = ele;
            }
            else 
            {
                i++;
            }
        }
        Console.WriteLine(String.Join(",", arr));
    }
}
}
// This code is contributed by
// Venkata VardhiReddy(venkata)
Javascript
// rearrange an array such that arr[i] = i.
function fixArray(arr, n)
{

    for (let 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++;
    }
    
    return arr;
}

// Driver Code

    let arr = [ -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 ];
    let n = arr.length;

    // Function Call
    let ans = fixArray(arr, n);
        
     // Prepare the output string
    let output = ans.join(" ");

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

// This Code is Contributed by ravi18131
PHP
<?php

// Function to rearrange an array such that arr[i] = i
function fixArray(&$arr, $n) {
    for ($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++;
        }
    }
}

// Driver Code
$arr = [ -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 ];
$n = count($arr);

// Function Call
fixArray($arr, $n);

// Print output
foreach ($arr as $value) {
    echo $value . " ";
}

// This Code is Contributed by ravi18131
?>

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

Time Complexity: O(n)
Auxiliary Space: O(1)

Another Approach (Using Vector) : 

Follow these steps to rearrange an array

  • Make a vector of size n and fill its every element by -1.
  • Now traverse the input array and if any element is not equal to -1 then
    • Fill that index of the vector which is equal to the element of the input array by that element’s value
  • In last copy all elements of the vector into the input array and then return or print that input array

Code-

C++
// C++ program for rearrange an
// array such that arr[i] = i.
#include <bits/stdc++.h>
using namespace std;

int* fixArray(int arr[], int n)
{
    vector<int> vec(n, -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;
}

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

    // Function Call
    fixArray(arr, n);

    // Print output
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    return 0;
}
Java
import java.util.*;

public class Main {
    static int[] fixArray(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
        fixArray(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 fixArray(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
  
# Driver code
arr = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]
n = len(arr)
  
# Function call
fixArray(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[] FixArray(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;
    }

    // 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
        FixArray(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 fixArray(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;
}

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

// Function Call
fixArray(arr);

// Print output
console.log(arr.join(" "));
PHP
<?php

// Function to rearrange an array such that arr[i] = i
function fixArray($arr, $n) {
    $vec = array_fill(0, $n, -1);

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

    for ($i = 0; $i < $n; $i++) {
        $arr[$i] = $vec[$i];
    }

    return $arr;
}

// Driver Code
$arr = [ -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 ];
$n = count($arr);

// Function Call
$arr = fixArray($arr, $n);

// Print output
foreach ($arr as $value) {
    echo $value . " ";
}

//This code is contributed by ravi18131
?>

Output-

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

Time Complexity: O(n)
Auxiliary Space: O(n),for vector



Previous Article
Next Article

Similar Reads

Count pairs (i, j) from an array such that |arr[i]| and |arr[j]| both lies between |arr[i] - arr[j]| and |arr[i] + arr[j]|
Given an array arr[] of size N, the task is to count the number of pairs (arr[i], arr[j]) such that |arr[i]| and |arr[j]| lies between |arr[i] - arr[j]| and |arr[i] + arr[j]|. Examples: Input: arr[] = {1, 3, 5, 7} Output: 2 Explanation: Pair (arr[1], arr[2]) (= (3, 5)) lies between |3 - 5| (= 2) and |3 + 5| (= 8).Pair (arr[2], arr[3]) (= (5, 7)) li
6 min read
Check whether (i,j) exists such that arr[i] != arr[j] and arr[arr[i]] is equal to arr[arr[j]]
Given an array A[]. The task is to determine if it is possible to choose two indices 'i' and 'j' such that the below conditions gets satisfied:- A[i] is not equal to A[j].A[A[i]] is equal to A[A[j]]. Note: The value of the elements in an array is less than the value of N i.e. For every i, arr[i] < N. Examples: Input: N = 4, A[] = {1, 1, 2, 3} Ou
10 min read
Maximum value of |arr[0] - arr[1]| + |arr[1] - arr[2]| + ... +|arr[n - 2] - arr[n - 1]| when elements are from 1 to n
Given an array arr[] of size n whose elements are from the range [1, n]. The task is to find maximum value of |arr[0] - arr[1]| + |arr[1] - arr[2]| + ... +|arr[n - 2] - arr[n - 1]|. You can arrange the numbers in the array in any order. Examples: Input: arr[] = {1, 2, 3, 4} Output: 7 Arrange the array in this way for max value, arr[] = {3, 1, 4, 2}
3 min read
Minimize last remaining element of Array by selecting pairs such that arr[i] >= arr[j] and replace arr[i] with arr[i] - arr[j]
Given an array arr[] of N positive integers, the task is to find the smallest possible value of the last remaining element in the array after performing the following operations any number of times: Select a pair of indices (i, j) such that arr[i] >= arr[j] and replace arr[i] with arr[i] - arr[j].If an array element arr[i] <= 0, remove it fro
5 min read
Rearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < i
Given an array of n elements. Our task is to write a program to rearrange the array such that elements at even positions are greater than all elements before it and elements at odd positions are less than all elements before it.Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 7} Output : 4 5 3 6 2 7 1 Input : arr[] = {1, 2, 1, 4, 5, 6, 8, 8} Output : 4
11 min read
Javascript Program to Rearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < i
Given an array of n elements. Our task is to write a program to rearrange the array such that elements at even positions are greater than all elements before it and elements at odd positions are less than all elements before it. Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 7}Output : 4 5 3 6 2 7 1Input : arr[] = {1, 2, 1, 4, 5, 6, 8, 8} Output : 4
3 min read
Count pairs in an array such that LCM(arr[i], arr[j]) > min(arr[i],arr[j])
Given an array arr[], the task is to find the count of pairs in the array such that LCM(arr[i], arr[j]) > min(arr[i], arr[j]) Note: Pairs (arr[i], arr[j]) and (arr[j], arr[i]) are considered identical and will be counted only once. Examples: Input: arr[] = {1, 1, 4, 9} Output: 5 All valid pairs are (1, 4), (1, 9), (1, 4), (1, 9) and (4, 9). Inpu
9 min read
Count quadruples (i, j, k, l) in an array such that i < j < k < l and arr[i] = arr[k] and arr[j] = arr[l]
Given an array arr[] consisting of N integers, the task is to count the number of tuples (i, j, k, l) from the given array such that i < j < k < l and arr[i] = arr[k] and arr[j] = arr[l]. Examples: Input: arr[] = {1, 2, 1, 2, 2, 2} Output: 4 Explanation: The tuples which satisfy the given condition are: 1) (0, 1, 2, 3) since arr[0] = arr[2
6 min read
Rearrange array to maximize count of triplets (i, j, k) such that arr[i] > arr[j] < arr[k] and i < j < k
Given an array, arr[] of size N, the task is to rearrange the array elements to maximize the count of triplets (i, j, k) that satisfy the condition arr[i] > arr[j] < arr[k] and i < j < k. Examples: Input: arr[] = {1, 4, 3, 3, 2, 2, 5} Output: Count of triplets: 3 Array: {3, 1, 3, 2, 4, 2, 5} Explanation:Rearrange the array to {3, 1, 3,
8 min read
Count number of pairs (i, j) such that arr[i] * arr[j] > arr[i] + arr[j]
Given an array arr[] of non-negative integers, the task is to count pairs of indices (i, j such that arr[i] * arr[j] > arr[i] + arr[j] where i < j. Examples: Input: arr[] = { 5, 0, 3, 1, 2 } Output: 3 Input: arr[] = { 1, 1, 1 } Output: 0 Naive Approach: Run two nested loops and check for every pair whether the condition is satisfied. If the c
9 min read
Count the number of pairs (i, j) such that either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i]
Given an array arr[] of N integers, the task is to find the count of unordered index pairs (i, j) such that i != j and 0 <=i < j < N and either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i]. Examples: Input: arr[] = {2, 4} Output: 1 (0, 1) is the only index pair possible. Input: arr[] = {3, 2, 4, 2, 6} Output: 6 Possible p
7 min read
Count number of pairs (i, j) such that arr[i] * arr[j] = arr[i] + arr[j]
Given an array arr[] of length N, count the number of pairs (i, j) such that arr[i] * arr[j] = arr[i] + arr[j] and 0 <= i < j <= N. It is also given that elements of the array can be any positive integers including zero. Examples: Input : arr[] = {2, 0, 3, 2, 0} Output : 2 Input : arr[] = {1, 2, 3, 4} Output : 0 Simple solution: We can gen
8 min read
Count of pairs (arr[i], arr[j]) such that arr[i] + j and arr[j] + i are equal
Given an array arr[], the task is to count pairs i, j such that, i < j and arr[i] + j = arr[j] + i. Examples: Input: arr[] = {4, 1, 2, 3}Output: 3Explanation: In total three pairs are satisfying the given condition those are {1, 2}, {2, 3} and {1, 3}.So, the final answer is 3. Input: arr[] = {1, 5, 6}Output: 1 Naive Approach: The naive approach
5 min read
Maximize arr[j] - arr[i] + arr[l] - arr[k], such that i < j < k < l
Maximize arr[j] - arr[i] + arr[l] - arr[k], such that i < j < k < l. Find the maximum value of arr[j] - arr[i] + arr[l] - arr[k], such that i < j < k < l Example: Let us say our array is {4, 8, 9, 2, 20} Then the maximum such value is 23 (9 - 4 + 20 - 2)Recommended PracticeMaximum valueTry It! Brute Force Method: We can simply fin
11 min read
Maximum value of (arr[i] * arr[j]) + (arr[j] - arr[i])) possible for any pair in an array
Given an array arr[] consisting of N integers, the task is to find the maximum possible value of the expression (arr[i] * arr[j]) + (arr[j] - arr[i])) for any pair (i, j), such that i ? j and 0 ? (i, j) < N. Examples: Input: arr[] = {-2, -8, 0, 1, 2, 3, 4}Output: 22Explanation:For the pair (-8, -2) the value of the expression (arr[i] * arr[j]) +
6 min read
Rearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space
Given an array arr[] of size n where every element is in the range from 0 to n-1. Rearrange the given array so that arr[i] becomes arr[arr[i]]. This should be done with O(1) extra space Examples: Input: arr[] = {3, 2, 0, 1}Output: arr[] = {1, 0, 3, 2}Explanation: In the given array arr[arr[0]] is 1 so arr[0] in output array is 1arr[arr[1]] is 0 so
7 min read
Check if an array arr[] can be rearranged such that arr[2 × i + 1] = 2* arr[2 × i] for every ith index
Given an array arr[] consisting of 2*N integers, the task is to check if it is possible to rearrange the array elements such that arr[2 * i + 1] = 2* arr[2 * i] for every ith index. If it is possible to do so, then print "Yes. Otherwise, print "No". Examples: Input: arr[] = {4, -2, 2, -4}, N = 2Output: YesExplanation: Rearrange the array as arr[] =
8 min read
Find a triplet (i, j, k) from an array such that i < j < k and arr[i] < arr[j] > arr[k]
Given an array arr[] which consists of a permutation of first N natural numbers, the task is to find any triplet (i, j, k) from the given array such that 0 ? i < j < k ? (N - 1) and arr[i] < arr[j] and arr[j] > arr[k]. If no such triplet exists, then print "-1". Examples: Input: arr[] = {4, 3, 5, 2, 1, 6}Output: 1 2 3Explanation: For th
5 min read
Given an array arr[], find the maximum j - i such that arr[i] <= arr[j]
Given an array arr[] of N positive integers. The task is to find the maximum of j - i subjected to the constraint of arr[i] <= arr[j]. Examples : Input: {34, 8, 10, 3, 2, 80, 30, 33, 1} Output: 6 (j = 7, i = 1) Input: {9, 2, 3, 4, 5, 6, 7, 8, 18, 0} Output: 8 ( j = 8, i = 0) Input: {1, 2, 3, 4, 5, 6} Output: 5 (j = 5, i = 0) Input: {6, 5, 4, 3,
15+ min read
Rearrange an array such that 'arr[j]' becomes 'i' if 'arr[i]' is 'j' | Set 1
Given an array of size n where all elements are distinct and in the range from 0 to n-1, change the 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 ch
15+ min read
Check whether there exists a triplet (i, j, k) such that arr[i] < arr[k] < arr[j] for i < j < k
Given an array arr[], the task is to check that if there exist a triplet (i, j, k) such that arr[i]<arr[k]<arr[j] and i<j<k then print Yes else print No. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: NoExplanation:There is no such sub-sequence such that arr[i] < arr[k] < arr[j] Input: arr[] = {3, 1, 5, 0, 4}Output: YesExplanatio
11 min read
Count pairs (i, j) from arrays arr[] & brr[] such that arr[i] - brr[j] = arr[j] - brr[i]
Given two arrays arr[] and brr[] consisting of N integers, the task is to count the number of pairs (i, j) from both the array such that (arr[i] – brr[j]) and (arr[j] – brr[i]) are equal. Examples: Input: A[] = {1, 2, 3, 2, 1}, B[] = {1, 2, 3, 2, 1} Output: 2 Explanation: The pairs satisfying the condition are: (1, 5): arr[1] - brr[5] = 1 - 1 = 0,
7 min read
Count of jumps to reach the end of Array by jumping from arr[i] to arr[arr[i]]
Given an array arr[] of N integers, the task is to find the number of jumps required to escape the array arr[] for all values of i as the starting indices in the range [0, N) where the only possible jump from arr[i] is to arr[arr[i]] and escaping the array means arr[i]>=N, i.e, the index for the next jump does not exist. Examples: Input: arr[] =
10 min read
Sort Array by choosing indices i, j, k and replacing arr[i] with arr[j] - arr[k]
Given an array arr[] of N integers, the task is to sort the array by replacing any element at index i (arr[i]) with arr[j] - arr[k] such that i < j < k. Note: If no operation is needed print 0. Examples: Input: arr[] = {2, -2, -3, -1, 3}Output:33 4 52 4 51 4 5Explanation: The number at 3rd position can be replaced by 4th and last position. Th
9 min read
Find Maximum value of abs(i - j) * min(arr[i], arr[j]) in an array arr[]
Given an array of n distinct elements. Find the maximum of product of Minimum of two numbers in the array and absolute difference of their positions, i.e., find maximum value of abs(i - j) * min(arr[i], arr[j]) where i and j vary from 0 to n-1. Examples : Input : arr[] = {3, 2, 1, 4} Output: 9 // arr[0] = 3 and arr[3] = 4 minimum of them is 3 and /
7 min read
Convert Array into Zig-Zag fashion (arr[i-1] < arr[i] > arr[i+1])
Given an array of distinct elements of size N, the task is to rearrange the elements of the array in a zig-zag fashion, i.e., the elements are arranged as smaller, then larger, then smaller, and so on. There can be more than one arrangement that follows the form: arr[0] < arr[1] > arr[2] < arr[3] > arr[4] < ... Examples: Input: N = 7
12 min read
Longest chain of arr[i], arr[arr[i]], .. without repetition
Given an array of size n such that elements in array are distinct and in range from 0 to n-1. We need to find out length of the longest chain {arr[i], arr[arr[i]], arr[arr[arr[i]]]......} such that no set element repeats. Examples: Input : arr[] = [5, 4, 0, 3, 1, 6, 2] Output :4 Explanation: The longest chain without repetition is {arr[0], arr[5],
7 min read
Maximum value of expression (arr[i] + arr[j] * arr[k]) formed from a valid Triplet
Given an array arr[] of N integers. The task is to find the maximum value of (arr[i] + arr[j] * arr[k]) among every triplet (i, j, k) such that arr[i] < arr[j] < arr[k] and i < j < k. If there doesn't exist any such triplets then print “-1". Examples: Input: arr[]={7, 9, 3, 8, 11, 10}Output: 106Explanation:The valid triplets are:1) (7,
14 min read
Find triplet (i, j, k) to maximize (P * arr[i] + Q * arr[j] + R * arr[k])
Given an array arr[] of size N and three numbers P, Q, and R. The task is to find three indices named (i, j, k) in the given array such that i < j < k, and the value of equation (P * arr[i] + Q * arr[j] + R * arr[k]) should be maximum. Examples: Input: arr[] = {1, 2, 3, 4, 5}, P = 1, Q = 2, R = 3Output: 2 3 4Explanation: For the given array t
15+ min read
Generate an N-length array A[] from an array arr[] such that arr[i] is the last index consisting of a multiple of A[i]
Given an array arr[] of length N, with values less than N, the task is to construct another array A[] of same length such that for every ith element in the array A[], arr[i] is the last index (1-based indexing) consisting of a multiple of A[i]. Examples: Input: arr[] = {4, 1, 2, 3, 4}Output: 2 3 5 7 2Explanation: A[0]: Last index which can contain
10 min read
Article Tags :
Practice Tags :