Related Articles

# Find permutation of [1, N] such that (arr[i] != i+1) and sum of absolute difference between arr[i] and (i+1) is minimum

• Last Updated : 17 Jul, 2021

Given a positive integer N, the task is to find the permutation of the first N natural numbers, say arr[] such that (arr[i] != i + 1) and the sum of the absolute difference between arr[i] and (i + 1) is minimum.

Examples:

Input: N = 4
Output: 2 1 4 3
Explanation:
Consider the permutation {2, 1, 4, 3}, Now, the sum is abs(2 – 1) + abs(1 – 2) + abs(4 – 3) + abs(3 – 4) = 1 + 1 + 1 + 1 = 4, which is minimum.

Input: N = 7
Output: 2 1 4 3 6 7 5

Naive Approach: The simplest approach to solve the given problem is to generate all possible permutations of the first N Natural Numbers and print that permutation that satisfies the given criteria.

Time Complexity: O(N!)
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized by observing the fact that the resultant array can be formed by swapping alternating adjacent pairs in order to allow the new position with the minimum sum of the absolute difference between arr[i] and (i +1). In case when N is greater than 1 and N is odd then the last element can be swapped by any of the second last or third last elements of the permutation. Follow the steps below to solve the given problem:

• Initialize an array, say arr[] with the first N natural number arranged in ascending order.
• Traverse the array and swap all the adjacent element as swap(arr[i], arr[i – 1]).
• Now, if the value of N is greater than 1 and N is odd then swap(arr[N – 1], arr[N – 2]).
• After completing the above steps, print the array arr[] as the resultant permutation.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `// Function to generate the permutation``// of the first N natural numbers having``// sum of absolute difference between``// element and indices as minimum``#include ``using` `namespace` `std;` `void` `swap(``int``& a, ``int``& b)``{``    ``int` `temp = a;``    ``a = b;``    ``b = temp;``}` `void` `findPermutation(``int` `N)``{``  ` `    ``// Initialize array arr[] from 1 to N``    ``int` `arr[N];``    ``for` `(``int` `i = 0; i < N; i++) {``        ``arr[i] = i + 1;``    ``}``    ``for` `(``int` `i = 1; i < N; i += 2) {``      ` `      ``// Swap alternate positions``        ``swap(arr[i], arr[i - 1]);``    ``}``  ` `  ``// Check N is greater than 1 and``    ``// N is odd``    ``if` `(N % 2 == 1 && N > 1) {``      ` `      ``// Swapping last two positions``        ``swap(arr[N - 1], arr[N - 2]);``    ``}` `   ``// Print the permutation``    ``for` `(``int` `i = 0; i < N; i++) {``        ``cout << arr[i] << ``" "``;``    ``}``}` `// Driver code``int` `main()``{``    ``int` `N = 7;``    ``findPermutation(N);``    ``return` `0;``}` `// This code is contributed by Parth Manchanda`

## Java

 `// Java program for the above approach` `// Function to generate the permutation``// of the first N natural numbers having``// sum of absolute difference between``// element and indices as minimum``import` `java.util.*;` `class` `GFG{` `static` `void` `findPermutation(``int` `N)``{``    ` `    ``// Initialize array arr[] from 1 to N``    ``int``[] arr = ``new` `int``[N];``    ``int` `temp;``    ` `    ``for``(``int` `i = ``0``; i < N; i++)``    ``{``        ``arr[i] = i + ``1``;``    ``}``    ``for``(``int` `i = ``1``; i < N; i += ``2``)``    ``{``        ` `        ``// Swap alternate positions``        ``temp = arr[i];``        ``arr[i] = arr[i - ``1``];``        ``arr[i - ``1``] = temp;``    ``}` `    ``// Check N is greater than 1 and``    ``// N is odd``    ``if` `(N % ``2` `== ``1` `&& N > ``1``)``    ``{``        ` `        ``// Swapping last two positions``        ``temp = arr[N - ``1``];``        ``arr[N - ``1``] = arr[N - ``2``];``        ``arr[N - ``2``] = temp;``    ``}` `    ``// Print the permutation``    ``for``(``int` `i = ``0``; i < N; i++)``    ``{``        ``System.out.print(arr[i] + ``" "``);``    ``}``}` `// Driver code``public` `static` `void` `main(String[] args)``{``    ``int` `N = ``7``;``    ` `    ``findPermutation(N);``}``}` `// This code is contributed by subhammahato348`

## Python3

 `# Python3 program for the above approach` `# Function to generate the permutation``# of the first N natural numbers having``# sum of absolute difference between``# element and indices as minimum``def` `findPermutation(N):` `    ``# Initialize array arr[] from 1 to N``    ``arr ``=` `[i ``+` `1` `for` `i ``in` `range``(N)]` `    ``# Swap alternate positions``    ``for` `i ``in` `range``(``1``, N, ``2``):``        ``arr[i], arr[i``-``1``] ``=` `arr[i``-``1``], arr[i]` `    ``# Check N is greater than 1 and``    ``# N is odd``    ``if` `N ``%` `2` `and` `N > ``1``:` `        ``# Swapping last two positions``        ``arr[``-``1``], arr[``-``2``] ``=` `arr[``-``2``], arr[``-``1``]` `    ``# Print the permutation``    ``for` `i ``in` `arr:``        ``print``(i, end ``=` `" "``)`  `# Driver Code``if` `__name__ ``=``=` `'__main__'``:` `    ``N ``=` `7``    ``findPermutation(N)`

## C#

 `// C# program for the above approach` `// Function to generate the permutation``// of the first N natural numbers having``// sum of absolute difference between``// element and indices as minimum``using` `System;``class` `GFG {` `    ``static` `void` `findPermutation(``int` `N)``    ``{` `        ``// Initialize array arr[] from 1 to N``        ``int``[] arr = ``new` `int``[N];``        ``int` `temp;``        ``for` `(``int` `i = 0; i < N; i++) {``            ``arr[i] = i + 1;``        ``}``        ``for` `(``int` `i = 1; i < N; i += 2) {` `            ``// Swap alternate positions``            ``temp = arr[i];``            ``arr[i] = arr[i - 1];``            ``arr[i - 1] = temp;``        ``}` `        ``// Check N is greater than 1 and``        ``// N is odd``        ``if` `(N % 2 == 1 && N > 1) {` `            ``// Swapping last two positions``            ``temp = arr[N - 1];``            ``arr[N - 1] = arr[N - 2];``            ``arr[N - 2] = temp;``        ``}` `        ``// Print the permutation``        ``for` `(``int` `i = 0; i < N; i++) {``            ``Console.Write(arr[i] + ``" "``);``        ``}``    ``}` `    ``// Driver code``    ``public` `static` `void` `Main()``    ``{``        ``int` `N = 7;``        ``findPermutation(N);``    ``}``}` `// This code is contributed by ukasp.`

## Javascript

 ``
Output:
`2 1 4 3 6 7 5`

Time Complexity: O(N)
Auxiliary Space: O(N)

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