Bird
Raised Fist0
Interview PrepbacktrackinghardAmazonGoogleFacebook

Permutation Sequence (Kth)

Choose your preparation mode4 modes available
📋
Problem

Imagine you have a list of tasks to perform in every possible order, but you want to quickly jump to the k-th order without enumerating all permutations.

Given n and k, return the k-th permutation sequence of the numbers [1, 2, ..., n] in lexicographical order. Input: two integers n and k. Output: a string representing the k-th permutation.

1 ≤ n ≤ 91 ≤ k ≤ n!
Edge cases: n = 1, k = 1 → output '1' (smallest input)k = 1 → output is the first permutation in ascending orderk = n! → output is the last permutation in descending order
</>
IDE
def getPermutation(n: int, k: int) -> str:public String getPermutation(int n, int k)string getPermutation(int n, int k)function getPermutation(n, k)
def getPermutation(n, k):
    # Write your solution here
    pass
class Solution {
    public String getPermutation(int n, int k) {
        // Write your solution here
        return "";
    }
}
#include <string>
using namespace std;

string getPermutation(int n, int k) {
    // Write your solution here
    return "";
}
function getPermutation(n, k) {
    // Write your solution here
}
0/9
Common Bugs to Avoid
Wrong: Wrong permutation string off by one positionOff-by-one error in k indexing (using zero-based vs one-based inconsistently).✅ Subtract 1 from k before factorial computations: k -= 1
Wrong: First permutation for all k valuesIgnoring k and always returning ascending order permutation.✅ Implement logic to select digits based on factorial divisions of k.
Wrong: Last permutation for all k valuesIgnoring k and always returning descending order permutation.✅ Implement logic to select digits based on factorial divisions of k.
Wrong: TLE or timeoutUsing brute force generation of all permutations for large n and k.✅ Use factorial number system direct computation to achieve O(n^2) time.
✓
Test Cases
t1_01basic
Input{"n":3,"k":3}
Expected"213"

The permutations of [1,2,3] in order are: 123, 132, 213, 231, 312, 321. The 3rd is '213'.

t1_02basic
Input{"n":4,"k":9}
Expected"2314"

The 9th permutation of [1,2,3,4] in lex order is '2314'.

t2_01edge
Input{"n":1,"k":1}
Expected"1"

With only one element, the only permutation is '1'.

t2_02edge
Input{"n":3,"k":1}
Expected"123"

The first permutation in lex order for n=3 is '123'.

t2_03edge
Input{"n":3,"k":6}
Expected"321"

The last permutation for n=3 (k=3!) is '321'.

t3_01corner
Input{"n":4,"k":14}
Expected"3142"

The 14th permutation of [1,2,3,4] is '3142'.

t3_02corner
Input{"n":5,"k":16}
Expected"14352"

The 16th permutation of [1,2,3,4,5] is '15432'.

t3_03corner
Input{"n":3,"k":4}
Expected"231"

The 4th permutation of [1,2,3] is '231'.

t4_01performance
Input{"n":9,"k":362880}
⏱ Performance - must finish in 2000ms

Maximum input size n=9, k=9! = 362880. Optimal O(n^2) factorial number system approach must complete within 2s.

Practice

(1/5)
1. Consider this modified code snippet for generating parentheses. Which line contains a subtle bug that can cause invalid sequences to be generated?
medium
A. Line with 'if close_count <= open_count:' condition
B. Line with 's.pop()' after backtrack calls
C. Line with 'if open_count < n:' condition
D. Line with 'if len(s) == 2 * n:' base case

Solution

  1. Step 1: Examine close_count condition

    The condition 'close_count <= open_count' allows adding ')' even when close_count equals open_count, which can produce invalid sequences.
  2. Step 2: Correct condition

    The correct condition is 'close_count < open_count' to ensure ')' is added only when there are unmatched '('.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Changing to '<' fixes invalid sequence generation [OK]
Hint: Close count must be strictly less than open count [OK]
Common Mistakes:
  • Using <= instead of < for close_count condition
  • Forgetting to pop after recursion
2. Consider the following buggy implementation of next permutation. Which line contains the subtle bug that causes incorrect output when the input array is in descending order?
medium
A. Line 5: if i >= 0:
B. Line 13-16: reversing the suffix after pivot
C. Line 10: nums[i], nums[j] = nums[j], nums[i]
D. Line 2: while i >= 0 and nums[i] >= nums[i + 1]: i -= 1

Solution

  1. Step 1: Identify the bug

    The comment indicates the reversal of the suffix is missing or incorrectly implemented, which is critical when the array is descending (no pivot found).
  2. Step 2: Analyze the reversal code

    The reversal loop runs regardless of whether i is -1, which causes incorrect behavior when the entire array is descending; the suffix should be reversed to the lowest permutation.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Missing or incorrect suffix reversal causes wrong output on descending arrays [OK]
Hint: Suffix reversal must always happen after pivot swap or when no pivot found [OK]
Common Mistakes:
  • Not reversing suffix after swap
  • Swapping with wrong element
  • Ignoring descending array edge case
3. What is the time complexity of the BFS approach for removing invalid parentheses from a string of length n, considering the worst case?
medium
A. O(n * 2^n) because there can be up to 2^n states and each validity check takes O(n)
B. O(n!) because permutations of removals are explored
C. O(2^n) because BFS explores all subsets of characters without repeated checks
D. O(n^2) because each level removes one character and checks validity in O(n)

Solution

  1. Step 1: Count possible states

    Each character can be either removed or kept, so up to 2^n possible strings can be generated.
  2. Step 2: Analyze per-state cost

    Each string requires an O(n) validity check, so total worst-case time is O(n * 2^n).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    2^n states times O(n) validity checks [OK]
Hint: 2^n states times O(n) validity checks [OK]
Common Mistakes:
  • Confusing O(n^2) with BFS complexity
  • Ignoring validity check cost
  • Assuming factorial complexity
4. Suppose the problem is modified so that digits can be repeated any number of times (reuse allowed), and you want to generate all letter combinations of length n from the given digits. Which modification to the algorithm correctly handles this reuse scenario?
hard
A. Modify backtracking to allow choosing the same digit multiple times by not incrementing the index after each choice until length n is reached
B. Sort digits and generate combinations by picking letters only once per digit
C. Use dynamic programming to store combinations of length k and build up to length n without reuse
D. Use the same iterative queue approach but do not advance the digit index; instead, for each combination, append letters from all digits repeatedly until length n is reached

Solution

  1. Step 1: Understand reuse requirement

    Allowing reuse means digits can be chosen multiple times to build combinations of length n.
  2. Step 2: Identify correct approach

    Backtracking can be modified to not increment the digit index after choosing a letter, allowing reuse until length n is reached.
  3. Step 3: Why other options fail

    Iterative queue approach as-is assumes fixed digit positions; DP without reuse does not handle repeated digits; sorting and picking once per digit ignores reuse.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Backtracking with flexible index handles reuse elegantly [OK]
Hint: Backtracking index controls reuse by not advancing [OK]
Common Mistakes:
  • Trying to reuse digits in iterative approach without index control
  • Ignoring reuse in DP or sorting
5. Suppose the problem is modified so that parentheses can be reused multiple times (e.g., you can insert removed parentheses back anywhere). Which of the following algorithmic changes correctly adapts the BFS approach to handle this variant?
hard
A. Switch to backtracking with memoization to explore insertions and removals explicitly, pruning invalid states
B. Use BFS as is, since it already explores all possible removals and insertions implicitly
C. Use a greedy approach to insert parentheses at earliest invalid positions without BFS or backtracking
D. Modify BFS to allow adding parentheses back by generating new states with insertions at every position

Solution

  1. Step 1: Understand reuse of parentheses

    Allowing reuse means we can insert parentheses anywhere, greatly increasing state space and complexity.
  2. Step 2: Analyze BFS suitability

    Standard BFS only removes characters; it does not handle insertions, so it cannot explore all states correctly.
  3. Step 3: Identify correct approach

    Backtracking with memoization can explicitly explore insertions and removals, pruning invalid states to handle reuse properly.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Backtracking with memoization handles insertions and pruning [OK]
Hint: Reuse requires explicit insertion exploration, not just removal BFS [OK]
Common Mistakes:
  • Assuming BFS handles insertions
  • Using greedy for complex insertions
  • Modifying BFS without pruning leads to explosion
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard