Monday, November 18, 2024
Google search engine
HomeData Modelling & AIFind permutation of such that (arr != i+1) and sum of...

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

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 <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 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




<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 minimum
function 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 code
var N = 7;
 
findPermutation(N);
 
// This code is contributed by SURENDRA_GANGWAR
 
</script>


Output: 

2 1 4 3 6 7 5

 

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments