703115. Rearrange to Make arr[i] = i

Easy

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:

  1. Sort the array in ascending order.
  2. Initialize two pointers: i (the current index) and j (the smallest unswapped element).
  3. Iterate through the sorted array:
    • If arr[i] is less than or equal to i, increment i.
    • Otherwise, swap arr[i] with arr[j] and increment both i and j.
  4. 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

View on GeeksforGeeks
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;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.