Open In App

Rearrange given array such that no array element is same as its index

Last Updated : 24 Feb, 2022
Comments
Improve
Suggest changes
1 Like
Like
Report

Given an array arr[] consisting of N distinct integers, the task is to rearrange the array such that no element is same as its index ( 1-based indexing ). If multiple solutions exist, print any one of them.

Examples:

Input: arr[] = {4, 2, 3, 1}
Output: 3 1 4 2
Explanation: The elements at indices {1, 2, 3, 4} are {3, 1, 4, 2} respectively.

Input: arr[] = {10, 20, 30, 40, 6}
Output: 6 10 20 30 40
Explanation: The elements at indices {1, 2, 3, 4, 5} are {6, 10, 20, 30, 40} respectively.

Approach: The idea is to use sorting and swap each adjacent pair of indices at any index i if arr[i] is equal to i. This is because, if arr[i] = i holds true, then definitely arr[i + 1] ? i and arr[i] ? i + 1 because arr[i + 1] > arr[i]. If the last element, arr[N] is equal to N, then swap arr[N] and arr[N - 1]. Follow the steps below to solve the problem:

  • Sort the array arr[] in the increasing order.
  • Traverse the array over the range [0, N - 2] using the variable i and check if arr[i] is the same as (i + 1) or not. If found to be true, then swap arr[i] and arr[i + 1].
  • Now, for the last array element, if arr[N] is same as N, then swap arr[N] and arr[N - 1].
  • After completing the above steps, print the modified array.

Below is the implementation of the above approach:

C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;

// Function to rearrange the array a[]
// such that none of the array elements
// is same as its index
void rearrangeArray(int a[], int n)
{
    // Sort the array
    sort(a, a + n);

    // Traverse the indices [0, N - 2]
    // of the given array
    for (int i = 0; i < n - 1; i++) {

        // Check if the current element
        // is equal to its index
        if (a[i] == i + 1) {

            // If found to be true, swap
            // current element with the
            // next element
            swap(a[i], a[i + 1]);
        }
    }

    // Check if the last element is
    // same as its index
    if (a[n - 1] == n) {

        // If found to be true, swap
        // current element with the
        // previous element
        swap(a[n - 1], a[n - 2]);
    }

    // Print the modified array
    for (int i = 0; i < n; i++) {
        cout << a[i] << " ";
    }
}

// Driver Code
int main()
{
    int arr[] = { 1, 5, 3, 2, 4 };
    int N = sizeof(arr) / sizeof(arr[0]);

    // Function Call
    rearrangeArray(arr, N);

    return 0;
}
Java Python3 C# JavaScript

Output: 
2 1 4 5 3

 

Time Complexity: O(N*log N)
Auxiliary Space: O(1)


Next Article

Similar Reads