KatInterview

60. Permutation Sequence

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the k-th lexicographical permutation of the numbers from 1 to n. A brute-force approach of generating all n! permutations and picking the k-th one would be too slow, as n! grows very rapidly. The constraints n <= 9 and k <= n! suggest a more direct, mathematical approach to construct the permutation digit by digit.

Solution

Permutation Sequence in Python

class Solution:
    def getPermutation(self, n: int, k: int) -> str:
        # Create a list of numbers from 1 to n.
        numbers = list(range(1, n + 1))
        
        # Create a list to store factorials.
        factorials = [1] * (n + 1)
        for i in range(2, n + 1):
            factorials[i] = factorials[i-1] * i

        # Convert k to be 0-indexed.
        k -= 1
        
        result = []

        # Determine each digit of the permutation from left to right.
        for i in range(n, 0, -1):
            # The permutations of the remaining (i-1) numbers are grouped into blocks of size (i-1)!.
            # Find the index of the correct number in the 'numbers' list.
            index = k // factorials[i - 1]

            # Pop the chosen number from the list and append it to the result.
            num = numbers.pop(index)
            result.append(str(num))

            # Update k to find the correct permutation in the next smaller group.
            k %= factorials[i - 1]

        return "".join(result)

Permutation Sequence in Java

class Solution {
    public String getPermutation(int n, int k) {
        // Create a list of numbers from 1 to n.
        List<Integer> numbers = new ArrayList<>();
        // Create an array to store factorials.
        int[] factorial = new int[n + 1];
        StringBuilder result = new StringBuilder();

        // Initialize factorials and numbers list.
        factorial[0] = 1;
        for (int i = 1; i <= n; i++) {
            // Calculate factorial i! = (i-1)! * i
            factorial[i] = factorial[i - 1] * i;
            // Add number i to the list.
            numbers.add(i);
        }

        // Convert k to be 0-indexed.
        k--;

        // Determine each digit of the permutation from left to right.
        for (int i = n; i >= 1; i--) {
            // The permutations of the remaining (i-1) numbers are grouped into blocks of size (i-1)!.
            // Find the index of the correct number in the 'numbers' list.
            int index = k / factorial[i - 1];

            // Append the chosen number to the result.
            result.append(numbers.get(index));

            // Remove the used number from the list.
            numbers.remove(index);

            // Update k to find the correct permutation in the next smaller group.
            k %= factorial[i - 1];
        }

        return result.toString();
    }
}

Permutation Sequence in C++

class Solution {
public:
    string getPermutation(int n, int k) {
        // Create a list of numbers from 1 to n.
        vector<int> numbers;
        // Create an array to store factorials.
        vector<int> factorial(n + 1);
        string result = "";

        // Initialize factorials and numbers list.
        factorial[0] = 1;
        for (int i = 1; i <= n; ++i) {
            // Calculate factorial i! = (i-1)! * i
            factorial[i] = factorial[i-1] * i;
            // Add number i to the list.
            numbers.push_back(i);
        }

        // Convert k to be 0-indexed.
        k--;

        // Determine each digit of the permutation from left to right.
        for (int i = n; i >= 1; --i) {
            // The permutations of the remaining (i-1) numbers are grouped into blocks of size (i-1)!.
            // Find the index of the correct number in the 'numbers' list.
            int index = k / factorial[i - 1];

            // Append the chosen number to the result.
            result += to_string(numbers[index]);

            // Remove the used number from the list.
            numbers.erase(numbers.begin() + index);

            // Update k to find the correct permutation in the next smaller group.
            k %= factorial[i - 1];
        }

        return result;
    }
};

Permutation Sequence in TypeScript

function getPermutation(n: number, k: number): string {
    // Create a list of numbers from 1 to n.
    const numbers: number[] = [];
    // Create an array to store factorials.
    const factorial: number[] = new Array(n + 1);
    let result = '';

    // Initialize factorials and numbers list.
    factorial[0] = 1;
    for (let i = 1; i <= n; i++) {
        // Calculate factorial i! = (i-1)! * i
        factorial[i] = factorial[i - 1] * i;
        // Add number i to the list.
        numbers.push(i);
    }

    // Convert k to be 0-indexed.
    k--;

    // Determine each digit of the permutation from left to right.
    for (let i = n; i >= 1; i--) {
        // The permutations of the remaining (i-1) numbers are grouped into blocks of size (i-1)!.
        // Find the index of the correct number in the 'numbers' list.
        const index = Math.floor(k / factorial[i - 1]);

        // Append the chosen number to the result.
        result += numbers[index];

        // Remove the used number from the list.
        numbers.splice(index, 1);

        // Update k to find the correct permutation in the next smaller group.
        k %= factorial[i - 1];
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.