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?- A. 4213 12345 54321
- B. 3214 12345 54312
- C. 3214 12345 54321
- 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
- Problem: Count permutations p of 1..n where for every position i (1-based) p[i] is divisible by i or i is divisible by p[i] (backtracking…
- Problem: Can all matchsticks form a square (every stick used exactly once)? Backtrack placing sticks (longest first) into 4 sides…
- Problem: Insert '+', '−' or '' between the digits (or leave digits joined) so the expression equals the target. Operands may not have…
- Problem: A thief robs houses arranged as a binary tree; robbing two directly linked houses triggers an alarm. Each node returns (best if…
- Problem: Place the minimum number of cameras on tree nodes so every node is monitored (a camera covers itself, its parent and its…
- Problem: A tree of n nodes holds n coins in total, unevenly. A move transfers one coin between adjacent nodes. Minimum moves so every node…