# Program to find kth lexicographic sequence from 1 to n of size k Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have two values n and k. Now consider a list of numbers in range 1 through n [1, 2, ..., n] and generating every permutation of this list in lexicographic sequence. For example, if n = 4 we have [1234, 1243, 1324, 1342, 1423, 1432, 2134, 2143, 2314, 2341, 2413, 2431, 3124, 3142, 3214, 3241, 3412, 3421, 4123, 4132, 4213, 4231, 4312, 4321]. We have to find the kth value of this permutation sequence as a string.

So, if the input is like n = 4 k = 5, then the output will be "1432"

To solve this, we will follow these steps −

• Define a function factors() . This will take num

• quo := num

• res := a double ended queue and insert 0 at beginning

• i := 2

• while quo is not empty, do

• quo := quotient of (quo / i), rem := quo mod i

• insert rem at the left of res

• i := i + 1

• return res

• From the main method do the following −

• numbers := a list with values 1 through n

• res := blank string

• k_fact := factors(k)

• while size of k_fact < size of numbers, do

• res := res concatenate first element of numbers as string, then delete first element of numbers

• for each index in k_fact, do

• number := index−th element of numbers, then remove that element

• res := res concatenate number

• return res

Let us see the following implementation to get better understanding −

## Example

Live Demo

from collections import deque
def factors(num):
quo = num
res = deque([0])
i = 2
while quo:
quo, rem = divmod(quo, i)
res.appendleft(rem)
i += 1
return res
class Solution:
def solve(self, n, k):
numbers = [num for num in range(1, n + 1)]
res = ""
k_fact = factors(k)
while len(k_fact) < len(numbers):
res += str(numbers.pop(0))
for index in k_fact:
number = numbers.pop(index)
res += str(number)
return res
ob = Solution()
n = 4
k = 5
print(ob.solve(n, k))

## Input

4, 5

## Output

1432
Updated on 26-Dec-2020 10:57:54