[
backtracking
math
]
BinarySearch 0680 Kth Permutation Sequence
Problem statement
https://binarysearch.com/problems/Kth-Permutation-Sequence/
Solution
Equal to Leetcode 0060. Permutation Sequence, but indexes start with 0
here.
Complexity
It is O(n^2)
for time and O(n)
for space.
Code
class Solution:
def solve(self, n, k):
numbers = list(range(1, n+1))
answer = ""
for n_it in range(n,0,-1):
d = k//factorial(n_it-1)
k -= d*factorial(n_it-1)
answer += str(numbers[d])
numbers.remove(numbers[d])
return answer