![]() |
VOOZH | about |
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.
Table of Content
The Idea is to place each element
iat indexiif it exists in the array.
For every indexi, linearly search the entire array to check whether the valueiis present.
If found, moveito indexiby swapping.
Ifiis not present in the array, assign-1to indexi.
Repeat this process for all indices to obtain the final rearranged array.
-1 1 2 3 4 -1 6 -1 -1 9
n and initialize all its elements to -1.arr[i] that is not -1, place it at index arr[i] in the auxiliary array.-1 1 2 3 4 -1 6 -1 -1 9
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
arr[i] is already at its correct position (arr[i] == i), move to the next index.arr[i] is not -1, swap it with the element at index arr[i].arr[i] may still be misplaced.arr[i] becomes -1 or the correct element is placed at index i.-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.