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

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 = 4Output: 2 1 4 3Explanation: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 = 7Output: 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++
Java
Python3
C#
Javascript
// 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 <iostream>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 codeint main(){    int N = 7;    findPermutation(N);    return 0;} // This code is contributed by Parth Manchanda
// 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 minimumimport 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 codepublic static void main(String[] args){    int N = 7;         findPermutation(N);}} // This code is contributed by subhammahato348
# 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 minimumdef 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 Codeif __name__ == '__main__':     N = 7    findPermutation(N)
// 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 minimumusing 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.
<script> // Javascript 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 minimumfunction findPermutation(N){    var i;         // Initialize array arr[] from 1 to N    var arr = new Array(N);    for(i = 0; i < N; i++)    {        arr[i] = i + 1;    }     for(i = 1; i < N; i += 2)    {                 // Swap alternate positions        var 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        var temp = arr[N - 1];        arr[N - 1] = arr[N - 2];        arr[N - 2] = temp;    }         // Print the permutation    for(i = 0; i < N; i++)    {        document.write(arr[i] + " ");    }} // Driver codevar N = 7; findPermutation(N); // This code is contributed by SURENDRA_GANGWAR </script>
2 1 4 3 6 7 5
 
Time Complexity: O(N)Auxiliary Space: O(N)
parthmanchanda81
ukasp
subhammahato348
SURENDRA_GANGWAR
permutation
Arrays
Mathematical
Arrays
Mathematical
permutation
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7