Permutation Sequence

Pattern: Permutations

hard

The permutations of 1..n, in order, come in blocks of (n - 1)! for each first digit. Divide k - 1 by that block size to choose the first digit, keep the remainder, and repeat with the digits left.

The problem

The n! permutations of the digits 1 to n, listed in increasing order, are numbered from 1. Given n and k, return the k-th one as a string. For example, n = 3, k = 3 gives "213" (the list is 123, 132, 213, 231, 312, 321), and n = 4, k = 9 gives "2314".

The function name getPermutation matches LeetCode. Use the link above for the exact statement and limits. The GFG link asks the same question.

Think first

  • How many permutations start with 1? With 2?
  • Which first digit does the k-th permutation have?
  • After choosing it, what problem is left?

Hints

    Brute force, and why it fails

    Generate permutations in order and stop at the k-th: O(k × n), up to O(n! × n). Counting blocks is O(n²).

    The key insight

    Sorted permutations are grouped by their first digit in equal-sized blocks. Knowing the block size turns "find the k-th" into a few divisions.

    Dry run

    k8
    digits1 2 3 4

    n = 4 and k = 9. Use k - 1 = 8, counting from 0. The digits are 1 2 3 4.

    Step 1 of 4

    The plan

    digits = [1 .. n], fact = n!, k = k - 1
    for i from n down to 1:
        fact = fact / i
        idx = k / fact
        append digits[idx]; remove it from digits
        k = k mod fact
    return the appended digits
    

    Complexity

    Time
    O(n²)
    Space
    O(n)

    n steps, each removing from a list of up to n digits.

    Edge cases

    • k = 1: 12…n.
    • k = n!: n…21.
    • n = 1: "1".
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public String getPermutation(int n, int k) {
            List<Integer> digits = new ArrayList<>();
            int fact = 1;
            for (int i = 1; i <= n; i++) { digits.add(i); fact *= i; }
            k--;                                            // count from 0
            StringBuilder out = new StringBuilder();
            for (int i = n; i >= 1; i--) {
                fact /= i;                                  // permutations of the remaining i - 1 digits
                int idx = k / fact;                         // how many whole blocks to skip
                out.append(digits.remove(idx));
                k %= fact;
            }
            return out.toString();
        }
    }

    C++

    class Solution {
    public:
        string getPermutation(int n, int k) {
            vector<int> digits;
            int fact = 1;
            for (int i = 1; i <= n; i++) { digits.push_back(i); fact *= i; }
            k--;                                            // count from 0
            string out;
            for (int i = n; i >= 1; i--) {
                fact /= i;                                  // permutations of the remaining i - 1 digits
                int idx = k / fact;                         // how many whole blocks to skip
                out += to_string(digits[idx]);
                digits.erase(digits.begin() + idx);
                k %= fact;
            }
            return out;
        }
    };

    Python

    class Solution:
        def getPermutation(self, n: int, k: int) -> str:
            digits = list(range(1, n + 1))
            fact = 1
            for i in range(1, n + 1):
                fact *= i
            k -= 1                                  # count from 0
            out = []
            for i in range(n, 0, -1):
                fact //= i                          # permutations of the remaining i - 1 digits
                idx = k // fact                     # how many whole blocks to skip
                out.append(str(digits.pop(idx)))
                k %= fact
            return "".join(out)

    Common mistakes

    • Forgetting to change k to 0-based.
    • Using the block size n! instead of (n - 1)! for the first digit.
    • Not removing the chosen digit from the list.

    Similar problems