Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Return the k-th permutation (1-based, lexicographic) of 1..n directly using the factorial number system.

Problem: Return the k-th permutation (1-based, lexicographic) of 1..n directly using the factorial number system.
from math import factorial
def kth_perm(n, k):
    nums = list(range(1, n + 1)); k -= 1; out = []
    for i in range(n, 0, -1):
        f = factorial(i - 1); idx, k = divmod(k, f)
        out.append(nums.pop(idx))
    return "".join(map(str, out))
print(kth_perm(4, 15), kth_perm(5, 1), kth_perm(5, 120))
What is printed?
  1. A. 4213 12345 54321
  2. B. 3214 12345 54312
  3. C. 3214 12345 54321
  4. D. 3241 12345 54321

Correct answer: C. 3214 12345 54321

With k − 1 = 14 and 3! = 6 permutations per leading digit: 14 // 6 = 2 → third remaining digit 3, remainder 2; 2 // 2! = 1 → second remaining of {1, 2, 4} = 2, remainder 0; then 1, 4 → 3214 (itertools agrees). k = 1 is the sorted order and k = n! the reverse. O(n²) with list pops instead of O(n!·n) enumeration.

More Coding Interview Problems questions

Exams that ask this topic