Open in App
Not now

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

• Last Updated : 24 Feb, 2022

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``]`   `    ``# Print the 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)

My Personal Notes arrow_drop_up
Related Articles
{"ft_lang_label":"__label__en","ft_lang_prob":0.57798225,"math_prob":0.9839521,"size":6409,"snap":"2023-14-2023-23","text_gpt3_token_len":2178,"char_repetition_ratio":0.15222482,"word_repetition_ratio":0.49824807,"special_character_ratio":0.39553753,"punctuation_ratio":0.1408759,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9998233,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-03-30T11:43:43Z\",\"WARC-Record-ID\":\"<urn:uuid:a7cc2c8a-dc30-4b8a-8473-e75e1737eadc>\",\"Content-Length\":\"297671\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:0b5fecd7-0093-41c7-afae-22f34b3ee6c4>\",\"WARC-Concurrent-To\":\"<urn:uuid:7bdc7d50-728b-4150-9b00-c10d0cab2a6c>\",\"WARC-IP-Address\":\"44.228.100.190\",\"WARC-Target-URI\":\"https://origin.geeksforgeeks.org/rearrange-given-array-such-that-no-array-element-is-same-as-its-index/?ref=lbp\",\"WARC-Payload-Digest\":\"sha1:G362UIQDCHGWVF7F5LSKNDDFLFNRYUVC\",\"WARC-Block-Digest\":\"sha1:B7ATVQG4J4WY6X5CW4YAYTCNDVOJ6JDJ\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-14/CC-MAIN-2023-14_segments_1679296949181.44_warc_CC-MAIN-20230330101355-20230330131355-00045.warc.gz\"}"}