703115. Rearrange to Make arr[i] = i
Here is the blog post:
Rearrange to Make arr[i] = i
Summary
Given an array, we need to rearrange it such that arr[i] equals i. This problem involves sorting and manipulation of elements in the array. The key concept here is the idea of reordering the array to satisfy this condition.
Detailed Explanation
The problem can be solved by sorting the array in ascending order and then iterating through the sorted array. We start from the beginning of the array, and for each element arr[i], we swap it with the smallest unswapped element that is greater than or equal to i. This ensures that arr[i] becomes i.
Here's a step-by-step breakdown:
- Sort the array in ascending order.
- Initialize two pointers:
i(the current index) andj(the smallest unswapped element). - Iterate through the sorted array:
- If
arr[i]is less than or equal toi, incrementi. - Otherwise, swap
arr[i]witharr[j]and increment bothiandj.
- If
- Repeat step 3 until the end of the array.
The time complexity for this solution is O(n log n) due to the sorting, where n is the length of the array. The space complexity is O(1), as we only use a constant amount of extra space.
Optimized Solutions
Java
public class RearrangeArray {
public static void rearrange(int[] arr) {
Arrays.sort(arr);
int i = 0, j = 0;
while (j < arr.length) {
if (arr[i] <= i) {
i++;
} else {
swap(arr, i, j);
i++;
j++;
}
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}