Input: arr[] = [10, 11, 12], index[] = [1, 0, 2]
Output: 11 10 12
Explanation: 10 moves to position 1, 11 to 0, and 12 stays at 2.
Input: arr[] = [1, 2, 3, 4], index[] = [3, 2, 0, 1]
Output: 3 4 2 1
Explanation: 1 moves to 3, 2 to 2, 3 to 0, 4 to 1.
Input: arr[] = [50, 40, 70, 60, 90], index[] = [3, 0, 4, 1, 2]
Output: 40 60 90 50 70
The idea is to pair each element in arr[] with its target position from index[] as a 2D array. These pairs are then sorted by index, which arranges elements in the order they should appear in the final array. After sorting, we extract only the values (second part of each pair) to build the reordered array.
The idea is use cyclic sort technique to reorder elements in the arr[] array based on the specified index[]. It iterates through the elements of arr[] and, for each element, continuously swaps it with the element at its correct position according to index[]. The process continues until each element is at its intended position, ensuring the desired order is achieved.
The idea is to reorder elements in-place without using extra space by encoding two numbers (original and new) into a single number. Since each element in arr[] is less than or equal to the maximum value, we pick value = max + 1 to ensure uniqueness when combining.
We update arr[index[i]] using -> arr[index[i]] += (arr[i] % value) * value, which embeds both current and new values in the same cell.
- The % value ensures we use the original value even after updates.
- The * value shifts the new value to a higher place (like storing digits).
In the final step, dividing every element by value removes the original part and leaves only the reordered value