VOOZH about

URL: https://www.geeksforgeeks.org/dsa/rearrange-array-arri/

⇱ Rearrange array to make arr[i] = i - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rearrange array to make arr[i] = i

Last Updated : 27 Jan, 2026

Given an array of elements of length n, ranging from 0 to n - 1. All elements may not be present in the array. If the element is not present then there will be -1 present in the array. Rearrange the array such that arr[i] = i and if i is not present, store -1 at that place.

Examples:

Input: arr[] = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]
Output: [-1, 1, 2, 3, 4, -1, 6, -1, -1, 9]
Explanation: In range 0 to 9, all except 0, 5, 7 and 8 are present. Hence, we print -1 instead of them.

Input: arr[] = [0, 1, 2, 3, 4, 5]
Output: [0, 1, 2, 3, 4, 5]
Explanation: In range 0 to 5, all number are present.

[Naive Approach] Rearranging Array Elements – O(n²) Time and O(1) Space

The Idea is to place each element i at index i if it exists in the array.
For every index i, linearly search the entire array to check whether the value i is present.
If found, move i to index i by swapping.
If i is not present in the array, assign -1 to index i.
Repeat this process for all indices to obtain the final rearranged array.


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

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

  • The Idea is to create an auxiliary array of size n and initialize all its elements to -1.
  • Traverse the input array, and for each value arr[i] that is not -1, place it at index arr[i] in the auxiliary array.
  • Finally, copy the auxiliary array back into the original array to obtain the rearranged array.

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

[Expected Approach] In-Place Rearrangement by Swapping – O(n) Time and O(1) Space

The idea is to rearrange the array in-place by repeatedly swapping elements until each element reaches its correct index, without using any extra space.

Steps

  1. Traverse the array from left to right.
  2. If the current element arr[i] is already at its correct position (arr[i] == i), move to the next index.
  3. If arr[i] is not -1, swap it with the element at index arr[i].
  4. After swapping, do not increment the index, as the new element at arr[i] may still be misplaced.
  5. Repeat the swapping process until either arr[i] becomes -1 or the correct element is placed at index i.
  6. Continue this process for all indices in the array.

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

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

Comment
Article Tags: