Related Articles

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

• Last Updated : 21 Apr, 2021

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 ``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);` `    ``// Function Call``    ``rearrangeArray(arr, N);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.util.*;` `class` `GFG{``    ` `// Function to rearrange the array a[]``// such that none of the array elements``// is same as its index``static` `void` `rearrangeArray(``int` `a[], ``int` `n)``{``    ` `    ``// Sort the array``    ``Arrays.sort(a);``    ` `    ``// 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``            ``int` `temp = a[i];``            ``a[i] = a[i + ``1``];``            ``a[i + ``1``] = temp;``        ``}``    ``}` `    ``// 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``        ``int` `temp = a[n - ``1``];``        ``a[n - ``1``] = a[n - ``2``];``        ``a[n - ``2``] = temp;``    ``}``    ` `    ``// Print the modified array``    ``for``(``int` `i = ``0``; i < n; i++)``    ``{``        ``System.out.print(a[i] + ``" "``);``    ``}``}` `// Driver Code``public` `static` `void` `main(String args[])``{``    ``int` `arr[] = { ``1``, ``5``, ``3``, ``2``, ``4` `};``    ``int` `N = arr.length;``    ` `    ``// Function Call``    ``rearrangeArray(arr, N);``}``}` `// This code is contributed by ipg2016107`

## Python3

 `# Python3 program for the above approach` `# Function to rearrange the array a[]``# such that none of the array elements``# is same as its index``def` `rearrangeArray(a, n):``  ` `    ``# Sort the array``    ``a ``=` `sorted``(a)` `    ``# Traverse the indices [0, N - 2]``    ``# of the given array``    ``for` `i ``in` `range``(n ``-` `1``):` `        ``# 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``            ``a[i], a[i ``+` `1``] ``=` `a[i ``+` `1``], a[i]` `    ``# 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``        ``a[n ``-` `1``], a[n ``-` `2``] ``=` `a[n ``-` `2``], a[n ``-` `1``]` `    ``# Prthe modified array``    ``for` `i ``in` `range``(n):``        ``print``(a[i], end ``=` `" "``)` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``arr ``=` `[``1``, ``5``, ``3``, ``2``, ``4``]``    ``N ``=` `len``(arr)` `    ``# Function Call``    ``rearrangeArray(arr, N)` `    ``# This code is contributed by mohit kumar 29`

## C#

 `// C# program for the above approach``using` `System;``public` `class` `GFG``{``    ` `// Function to rearrange the array []a``// such that none of the array elements``// is same as its index``static` `void` `rearrangeArray(``int` `[]a, ``int` `n)``{``    ` `    ``// Sort the array``    ``Array.Sort(a);``    ` `    ``// 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``            ``int` `temp = a[i];``            ``a[i] = a[i + 1];``            ``a[i + 1] = temp;``        ``}``    ``}` `    ``// 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``        ``int` `temp = a[n - 1];``        ``a[n - 1] = a[n - 2];``        ``a[n - 2] = temp;``    ``}``    ` `    ``// Print the modified array``    ``for``(``int` `i = 0; i < n; i++)``    ``{``        ``Console.Write(a[i] + ``" "``);``    ``}``}` `// Driver Code``public` `static` `void` `Main(String []args)``{``    ``int` `[]arr = { 1, 5, 3, 2, 4 };``    ``int` `N = arr.Length;``    ` `    ``// Function Call``    ``rearrangeArray(arr, N);``}``}` `// This code is contributed by 29AjayKumar`

## Javascript

 ``
Output:
`2 1 4 5 3`

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up