![]() |
VOOZH | about |
Given an array arr[] of size n, where all elements are distinct and fall within the range 0 to n-1. The task is to modify arr[] such that if arr[i] = j, then it gets transformed into arr[j] = i.
Examples:
Input: arr[] = [1, 3, 0, 2]
Output: 2 0 3 1
Explanation: Since arr[0] = 1, update arr[1] to 0
Since arr[1] = 3, update arr[3] to 1
Since arr[2] = 0, update arr[0] to 2
Since arr[3] = 2, update arr[2] to 3Input: arr[] = [2, 0, 1, 4, 5, 3]
Output: 1 2 0 5 3 4
Explanation: Since arr[0] = 2, update arr[2] to 0
Since arr[1] = 0, update arr[0] to 1
Since arr[2] = 1, update arr[1] to 2
Since arr[3] = 4, update arr[4] to 3
Since arr[4] = 5, update arr[5] to 4
Since arr[5] = 3, update arr[3] to 5Input: arr[] = [3, 2, 1, 0]
Output: 3 2 1 0
Explanation: Since each element is already at its correct index, the array remains unchanged.
Table of Content
The idea is to use an extra array to directly place each element at its correct index without modifying the input during traversal. By observing that each element arr[i] represents its future index, we create a newArr where newArr[arr[i]] = i. Finally, we copy newArr back to arr to complete the rearrangement efficiently.
1 2 0 5 3 4
The idea is to transform in the form of cycles. For example, there are two cycles in {2, 0, 1, 4, 5, 3}. One cycle is (2, 0, 1) and other cycle is (4, 5, 3). The idea is to process all cycles one by one. To check whether an element is processed or not, we change the value of processed items arr[i] as -arr[i]. Since 0 can not be made negative, we first change all arr[i] to arr[i] + 1. In the end, we make all values positive and subtract 1 to get old values back.
Steps to implement the above idea:
1 2 0 5 3 4
The time complexity of this method seems to be more than O(n) at first look. If we take a closer look, we can notice that no element is processed more than a constant number of times.
The idea is to store both the old and new values within the same array using modulo and multiplication. Each element is updated such that arr[arr[i] % n] accumulates the new position while preserving the original value. After processing, the new values are extracted by performing integer division with n. This ensures an in-place transformation without using extra space.
1 2 0 5 3 4