Rearrange an array such that arr[i] = i
Last Updated :
26 Nov, 2024
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem