Sunday, August 31, 2025
HomeData Modelling & AIK difference permutation

K difference permutation

Given two integers n and k. Consider first permutation of natural n numbers, P = “1 2 3 … n”, print a permutation “Result” such that abs(Resulti – Pi) = k where Pi denotes the position of i in permutation P. The value of Pi varies from 1 to n. If there are multiple possible results, then print the lexicographically smallest one.
 

Input: n = 6 k = 3
Output: 4 5 6 1 2 3
Explanation:
     P = 1 2 3 4 5 6
Result = 4 5 6 1 2 3
We can notice that the difference between
individual numbers (at same positions) of 
P and result is 3 and "4 5 6 1 2 3" is 
lexicographically smallest such permutation.
Other greater permutations could be 

Input  : n = 6 k = 2
Output : Not possible
Explanation: No permutation is possible 
with difference is k 

 

Naive approach is to generate all the permutation from 1 to n and pick the smallest one which satisfy the condition of absolute difference k. Time complexity of this approach is ?(n!) which will definitely time out for large value of n.
The Efficient approach is to observe the pattern at each position of index. For each position of index i, there can only exist two candidate i.e., i + k and i – k. As we need to find lexicographically smallest permutation so we will first look for i – k candidate(if possible) and then for i + k candidate. 

 Illustration:
 n = 8, k = 2
 P : 1 2 3 4 5 6 7 8

 For any ith position we will check which candidate
 is possible i.e., i + k or i - k 

 1st pos = 1 + 2 = 3 (1 - 2 not possible)
 2nd pos = 2 + 2 = 4 (2 - 2 not possible)
 3rd pos = 3 - 2 = 1 (possible)
 4th pos = 4 - 2 = 2 (possible)
 5th pos = 5 + 2 = 7 (5 - 2 already placed, not possible)
 6th pos = 6 + 2 = 8 (6 - 2 already placed, not possible)
 7th pos = 7 - 2 = 5 (possible)
 8th pos = 8 - 2 = 6 (possible)

Note: If we observe above illustration then we will find that i + k and i – k are alternating after kth consecutive interval. Another observation is that the whole permutation is only when n is even such that n can be divided into two parts where each part must be divisible by k. 
 

C++




// C++ program to find k absolute difference
// permutation
#include<bits/stdc++.h>
using namespace std;
  
void kDifferencePermutation(int n, int k)
{
    // If k is 0 then we just print the
    // permutation from 1 to n
    if (!k)
    {
        for (int i = 0; i < n; ++i)
            cout << i + 1 << " ";
    }
  
    // Check whether permutation is feasible or not
    else if (n % (2 * k) != 0)
        cout <<"Not Possible";
  
    else
    {
        for (int i = 0; i < n; ++i)
        {
            // Put i + k + 1 candidate if position is
            // feasible, otherwise put the i - k - 1
            // candidate
            if ((i / k) % 2 == 0)
                cout << i + k + 1 << " ";
            else
                cout << i - k + 1 << " ";
        }
    }
    cout << "\n";
}
  
// Driver code
int main()
{
    int n = 6 , k = 3;
    kDifferencePermutation(n, k);
  
    n = 6 , k = 2;
    kDifferencePermutation(n, k);
  
    n = 8 , k = 2;
    kDifferencePermutation(n, k);
  
    return 0;
}


Java




// Java program to find k absolute
// difference permutation
import java.io.*;
  
class GFG {
  
    static void kDifferencePermutation(int n,
                                    int k)
    {
        // If k is 0 then we just print the
        // permutation from 1 to n
        if (!(k > 0))
        {
            for (int i = 0; i < n; ++i)
                System.out.print( i + 1 + " ");
        }
      
        // Check whether permutation is
        // feasible or not
        else if (n % (2 * k) != 0)
            System.out.print("Not Possible");
      
        else
        {
            for (int i = 0; i < n; ++i)
            {
                // Put i + k + 1 candidate
                // if position is feasible,
                // otherwise put the
                // i - k - 1 candidate
                if ((i / k) % 2 == 0)
                    System.out.print( i + k 
                            + 1 + " ");
                else
                    System.out.print( i - k 
                            + 1 + " ");
            }
        }
        System.out.println() ;
    }
      
    // Driver code
    static public void main (String[] args)
    {
        int n = 6 , k = 3;
        kDifferencePermutation(n, k);
      
        n = 6 ;
        k = 2;
        kDifferencePermutation(n, k);
      
        n = 8 ;
        k = 2;
        kDifferencePermutation(n, k);
    }
}
  
// This code is contributed by anuj_67.


Python3




# Python 3 program to find k 
# absolute difference permutation
def kDifferencePermutation(n, k):
      
    # If k is 0 then we just print the
    # permutation from 1 to n
    if (k == 0):
        for i in range(n):
            print(i + 1, end = " ")
  
    # Check whether permutation
    # is feasible or not
    elif (n % (2 * k) != 0):
        print("Not Possible", end = "")
  
    else:
        for i in range(n):
              
            # Put i + k + 1 candidate if position is
            # feasible, otherwise put the i - k - 1
            # candidate
            if (int(i / k) % 2 == 0):
                print(i + k + 1, end = " ")
            else:
                print(i - k + 1, end = " ")
  
    print("\n", end = "")
  
# Driver code
if __name__ == '__main__':
    n = 6
    k = 3
    kDifferencePermutation(n, k)
  
    n = 6
    k = 2
    kDifferencePermutation(n, k)
  
    n = 8
    k = 2
    kDifferencePermutation(n, k)
      
# This code is contributed by
# Surendra_Gangwar


C#




// C# program to find k absolute
// difference permutation
using System;
  
class GFG {
  
    static void kDifferencePermutation(int n,
                                       int k)
    {
        // If k is 0 then we just print the
        // permutation from 1 to n
        if (!(k > 0))
        {
            for (int i = 0; i < n; ++i)
                Console.Write( i + 1 + " ");
        }
      
        // Check whether permutation is
        // feasible or not
        else if (n % (2 * k) != 0)
            Console.Write("Not Possible");
      
        else
        {
            for (int i = 0; i < n; ++i)
            {
                // Put i + k + 1 candidate
                // if position is feasible,
                // otherwise put the
                // i - k - 1 candidate
                if ((i / k) % 2 == 0)
                    Console.Write( i + k 
                              + 1 + " ");
                else
                    Console.Write( i - k 
                              + 1 + " ");
            }
        }
        Console.WriteLine() ;
    }
      
    // Driver code
    static public void Main ()
    {
        int n = 6 , k = 3;
        kDifferencePermutation(n, k);
      
        n = 6 ;
        k = 2;
        kDifferencePermutation(n, k);
      
        n = 8 ;
        k = 2;
        kDifferencePermutation(n, k);
    }
}
  
// This code is contributed by anuj_67.


PHP




<?php
// PHP program to find k absolute 
// difference permutation
  
function kDifferencePermutation( $n, $k)
{
      
    // If k is 0 then we just print the
    // permutation from 1 to n
    if (!$k)
    {
        for($i = 0; $i < $n; ++$i)
            echo $i + 1 ," ";
    }
  
    // Check whether permutation
    // is feasible or not
    else if ($n % (2 * $k) != 0)
        echo"Not Possible";
  
    else
    {
        for($i = 0; $i < $n; ++$i)
        {
              
            // Put i + k + 1 candidate
            // if position is feasible, 
            // otherwise put the i - k - 1
            // candidate
            if (($i / $k) % 2 == 0)
                echo $i + $k + 1 , " ";
            else
                echo $i - $k + 1 , " ";
        }
    }
    echo "\n";
}
  
    // Driver Code
    $n = 6 ; $k = 3;
    kDifferencePermutation($n, $k);
  
    $n = 6 ; $k = 2;
    kDifferencePermutation($n, $k);
  
    $n = 8 ;$k = 2;
    kDifferencePermutation($n, $k);
  
// This code is contributed by anuj_67.
?>


Javascript




<script>
    // Javascript program to find k absolute difference permutation
      
    function kDifferencePermutation(n, k)
    {
        // If k is 0 then we just print the
        // permutation from 1 to n
        if (!(k > 0))
        {
            for (let i = 0; i < n; ++i)
                document.write( i + 1 + " ");
        }
        
        // Check whether permutation is
        // feasible or not
        else if (n % (2 * k) != 0)
            document.write("Not Possible");
        
        else
        {
            for (let i = 0; i < n; ++i)
            {
                // Put i + k + 1 candidate
                // if position is feasible,
                // otherwise put the
                // i - k - 1 candidate
                if (parseInt(i / k, 10) % 2 == 0)
                    document.write( i + k 
                              + 1 + " ");
                else
                    document.write( i - k 
                              + 1 + " ");
            }
        }
        document.write("</br>") ;
    }
      
    let n = 6 , k = 3;
    kDifferencePermutation(n, k);
  
    n = 6 ;
    k = 2;
    kDifferencePermutation(n, k);
  
    n = 8 ;
    k = 2;
    kDifferencePermutation(n, k);
   
 // This code is contributed by rameshtravel07.
</script>


Output: 
 

4 5 6 1 2 3 
Not Possible
3 4 1 2 7 8 5 6 

Time complexity: O(n) 
Auxiliary space: O(1)
This article is contributed by Shubham Bansal. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

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

Dominic
32250 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6619 POSTS0 COMMENTS
Nicole Veronica
11792 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11841 POSTS0 COMMENTS
Shaida Kate Naidoo
6735 POSTS0 COMMENTS
Ted Musemwa
7016 POSTS0 COMMENTS
Thapelo Manthata
6689 POSTS0 COMMENTS
Umr Jansen
6706 POSTS0 COMMENTS