8. Rearrange an array so that arr[i] becomes arr[arr[i]]
with O(1) extra space
Given an array arr[] of size n where every element is in range from 0 to n-1. Rearrange the given array so that arr[i] becomes arr[arr[i]]. This should be done with O(1) extra space.
Solution:
Approach: Increment every element at ith index is incremented by (arr[arr[i]] % n)*n Old value can be obtained by arr[i]%n and a new value can be obtained by arr[i]/n
Time Complexity: O(n)
Last updated