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):
- NavÂiÂgate the numbers from 0 to n-1.
- Now navigate through array.
- If (i==a[j]) , then replace the element at i position with a[j] position.
- If there is any element in which -1 is used instead of the number then it will be replaced automatically.
- 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++
#include <iostream>
using namespace std;
void fixArray( int ar[], int n)
{
int i, j, temp;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (ar[j] == i) {
temp = ar[j];
ar[j] = ar[i];
ar[i] = temp;
break ;
}
}
}
for (i = 0; i < n; i++)
{
if (ar[i] != i)
{
ar[i] = -1;
}
}
cout << "Array after Rearranging" << endl;
for (i = 0; i < n; i++) {
cout << ar[i] << " " ;
}
}
int main()
{
int n, ar[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
n = sizeof (ar) / sizeof (ar[0]);
fixArray(ar, n);
}
|
C
#include <stdio.h>
void fixArray( int ar[], int n)
{
int i, j, temp;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (ar[j] == i) {
temp = ar[j];
ar[j] = ar[i];
ar[i] = temp;
break ;
}
}
}
for (i = 0; i < n; i++)
{
if (ar[i] != i)
{
ar[i] = -1;
}
}
printf ( "Array after Rearranging\n" );
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]);
fixArray(ar, n);
}
|
Java
public class GFG{
public static void fixArray( int ar[], int n)
{
int i, j, temp;
for (i = 0 ; i < n; i++)
{
for (j = 0 ; j < n; j++)
{
if (ar[j] == i)
{
temp = ar[j];
ar[j] = ar[i];
ar[i] = temp;
break ;
}
}
}
for (i = 0 ; i < n; i++)
{
if (ar[i] != i)
{
ar[i] = - 1 ;
}
}
System.out.println( "Array after Rearranging" );
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;
fixArray(ar, n);
}
}
|
Python3
def fixArray(ar, n):
for i in range (n):
for j in range (n):
if (ar[j] = = i):
ar[j], ar[i] = ar[i], ar[j]
for i in range (n):
if (ar[i] ! = i):
ar[i] = - 1
print ( "Array after Rearranging" )
for i in range (n):
print (ar[i], end = " " )
ar = [ - 1 , - 1 , 6 , 1 , 9 , 3 , 2 , - 1 , 4 , - 1 ]
n = len (ar)
fixArray(ar, n);
|
C#
using System;
class GFG {
static void fixArray( int [] ar, int n)
{
int i, j, temp;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (ar[j] == i)
{
temp = ar[j];
ar[j] = ar[i];
ar[i] = temp;
break ;
}
}
}
for (i = 0; i < n; i++)
{
if (ar[i] != i)
{
ar[i] = -1;
}
}
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;
fixArray(ar, n);
}
}
|
Javascript
<script>
function fixArray(ar, n) {
var i, j, temp;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (ar[j] == i) {
temp = ar[j];
ar[j] = ar[i];
ar[i] = temp;
break ;
}
}
}
for (i = 0; i < n; i++)
{
if (ar[i] != i) {
ar[i] = -1;
}
}
document.write( "Array after Rearranging" );
document.write( "<br>" );
for (i = 0; i < n; i++) {
document.write(ar[i] + " " );
}
}
var n,
ar = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1];
n = ar.length;
fixArray(ar, n);
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
void fixArray( int A[], int len)
{
for ( int i = 0; i < len; i++)
{
if (A[i] != -1 && A[i] != i)
{
int x = A[i];
while (A[x] != -1 && A[x] != x)
{
int y = A[x];
A[x] = x;
x = y;
}
A[x] = x;
if (A[i] != i)
{
A[i] = -1;
}
}
}
}
int main()
{
int A[] = { -1, -1, 6, 1, 9,
3, 2, -1, 4, -1 };
int len = sizeof (A) / sizeof (A[0]);
fixArray(A, len);
for ( int i = 0; i < len; i++)
cout << A[i] << " " ;
}
|
Java
import java.util.*;
import java.lang.*;
public class GfG {
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];
while (A[x] != - 1 && A[x] != x)
{
int y = A[x];
A[x] = x;
x = y;
}
A[x] = x;
if (A[i] != i)
{
A[i] = - 1 ;
}
}
}
return A;
}
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)));
}
}
|
C
#include <stdio.h>
void fixArray( int A[], int len)
{
for ( int i = 0; i < len; i++)
{
if (A[i] != -1 && A[i] != i)
{
int x = A[i];
while (A[x] != -1 && A[x] != x)
{
int y = A[x];
A[x] = x;
x = y;
}
A[x] = x;
if (A[i] != i)
{
A[i] = -1;
}
}
}
}
int main()
{
int A[] = { -1, -1, 6, 1, 9,
3, 2, -1, 4, -1 };
int len = sizeof (A) / sizeof (A[0]);
fixArray(A, len);
for ( int i = 0; i < len; i++)
printf ( "%d " ,A[i]);
}
|
Python3
def fix(A, len ):
for i in range ( 0 , len ):
if (A[i] ! = - 1 and A[i] ! = i):
x = A[i]
while (A[x] ! = - 1 and A[x] ! = x):
y = A[x]
A[x] = x
x = y
A[x] = x
if (A[i] ! = i):
A[i] = - 1
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 = ' ' )
|
C#
using System;
class GfG {
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];
while (A[x] != -1 && A[x] != x)
{
int y = A[x];
A[x] = x;
x = y;
}
A[x] = x;
if (A[i] != i)
{
A[i] = -1;
}
}
}
return A;
}
static void Main()
{
int [] A = new int [] { -1, -1, 6, 1, 9,
3, 2, -1, 4, -1 };
Console.WriteLine( string .Join( "," , fix(A)));
}
}
|
PHP
<?php
function fix(& $A , $len )
{
for ( $i = 0; $i < $len ; $i ++)
{
if ( $A [ $i ] != -1 &&
$A [ $i ] != $i )
{
$x = $A [ $i ];
while ( $A [ $x ] != -1 &&
$A [ $x ] != $x )
{
$y = $A [ $x ];
$A [ $x ] = $x ;
$x = $y ;
}
$A [ $x ] = $x ;
if ( $A [ $i ] != $i )
{
$A [ $i ] = -1;
}
}
}
}
$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 ]. " " );
?>
|
Javascript
<script>
function fix(A, len)
{
for (let i = 0; i < len; i++)
{
if (A[i] != -1 &&
A[i] != i)
{
let x = A[i];
while (A[x] != -1 &&
A[x] != x)
{
let y = A[x];
A[x] = x;
x = y;
}
A[x] = x;
if (A[i] != i)
{
A[i] = -1;
}
}
}
}
let A = new Array(-1, -1, 6, 1, 9,
3, 2, -1, 4, -1);
let len = A.length;
fix(A, len);
for (let i = 0; i < len; i++)
document.write(A[i] + " " );
</script>
|
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)
{
unordered_set< int > s;
for ( int i=0; i<n; i++)
{
if (arr[i] != -1)
s.insert(arr[i]);
}
for ( int i=0; i<n; i++)
{
if (s.find(i) != s.end())
{
arr[i] = i;
}
else
{
arr[i] = -1;
}
}
}
int main() {
int arr[] {-1, -1, 6, 1, 9,
3, 2, -1, 4,-1};
int n = sizeof (arr) / sizeof (arr[0]);
fixArray(arr, n);
for ( int i=0; i<n; i++)
cout << arr[i] << ' ' ;
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
class GfG {
public static int [] fix( int [] A)
{
Set<Integer> s = new HashSet<Integer>();
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;
}
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)));
}
}
|
Python3
def fix(A):
s = set ()
for i in range ( len (A)):
s.add(A[i])
for i in range ( len (A)):
if i in s:
A[i] = i
else :
A[i] = - 1
return A
if __name__ = = "__main__" :
A = [ - 1 , - 1 , 6 , 1 , 9 ,
3 , 2 , - 1 , 4 , - 1 ]
print (fix(A))
|
C#
using System;
using System.Collections.Generic;
public class main{
static void fix( int [] a, int n){
HashSet< int > hs= new HashSet< int >();
for ( int i=0;i<n;i++)
hs.Add(a[i]);
for ( int i=0;i<n;i++)
{
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
<script>
function fix(A)
{
let s = new Set();
for (let i = 0; i < A.length; i++)
{
s.add(A[i]);
}
for (let i = 0; i < A.length; i++)
{
if (s.has(i))
A[i] = i;
else
A[i] = -1;
}
return A;
}
let A = [-1, -1, 6, 1, 9, 3, 2, -1, 4,-1];
let ans = fix(A);
for (let i = 0; i < ans.length; i++)
{
document.write(ans[i] + " " );
}
</script>
|
Output
-1 1 2 3 4 -1 6 -1 -1 9
Time Complexity: O(n2)
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++
#include <iostream>
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]) {
swap(arr[i], arr[correct]);
}
else {
i++;
}
}
return arr;
}
int main()
{
int arr[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
int n = sizeof (arr) / sizeof (arr[0]);
fixArray(arr, n);
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
return 0;
}
|
C
#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++;
}
}
int main()
{
int arr[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
int n = sizeof (arr) / sizeof (arr[0]);
fixArray(arr, n);
for ( int i = 0; i < n; i++)
printf ( "%d " , arr[i]);
return 0;
}
|
Java
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));
}
}
|
Python3
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 = " " )
|
C#
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));
}
}
}
|
Javascript
<script>
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++;
}
}
let arr = [ -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 ];
let n = arr.length;
fixArray(arr, n);
for (let i = 0; i < n; i++)
document.write(arr[i] + " " );
</script>
|
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++
#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;
}
int main()
{
int arr[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
int n = sizeof (arr) / sizeof (arr[0]);
fixArray(arr, n);
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;
}
public static void main(String[] args)
{
int arr[] = { - 1 , - 1 , 6 , 1 , 9 , 3 , 2 , - 1 , 4 , - 1 };
int n = arr.length;
fixArray(arr, n);
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
}
}
|
Python3
def fixArray(arr, n):
vec = [ - 1 ] * n
for i in range ( 0 , n):
if (arr[i] ! = - 1 ):
vec[arr[i]] = arr[i]
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)
fixArray(arr, n)
for i in range ( 0 , n):
print (arr[i], end = " " )
|
C#
using System;
class GFG
{
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;
}
public static void Main( string [] args)
{
int [] arr = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
int n = arr.Length;
FixArray(arr, n);
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
}
}
|
Javascript
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;
}
let arr = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1];
fixArray(arr);
console.log(arr.join( " " ));
|
Output-
-1 1 2 3 4 -1 6 -1 -1 9
Time Complexity: O(n)
Auxiliary Space: O(n),for vector
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
11 Apr, 2023
Like Article
Save Article