1. Brute Force (Backtracking)

class Solution:
    def getPermutation(self, n: int, k: int) -> str:
        used = [False] * (n + 1)
        path = []

        def dfs():
            nonlocal k
            if len(path) == n:
                k -= 1
                return k == 0
            for d in range(1, n + 1):
                if used[d]:
                    continue
                used[d] = True
                path.append(str(d))
                if dfs():
                    return True
                path.pop()
                used[d] = False
            return False

        dfs()
        return "".join(path)

Time & Space Complexity

  • Time complexity: O(n!∗n)O(n! * n) in the worst case (k=n!k = n!).
  • Space complexity: O(n)O(n) for the recursion stack, the used array and the current path.

Where nn is the number of digits and kk is the 1-based rank of the permutation.


2. Next Permutation

class Solution:
    def getPermutation(self, n: int, k: int) -> str:
        perm = [str(i) for i in range(1, n + 1)]
        for _ in range(k - 1):
            i = n - 2
            while perm[i] >= perm[i + 1]:
                i -= 1
            j = n - 1
            while perm[j] <= perm[i]:
                j -= 1
            perm[i], perm[j] = perm[j], perm[i]
            perm[i + 1:] = reversed(perm[i + 1:])
        return "".join(perm)

Time & Space Complexity

  • Time complexity: O(k∗n)O(k * n), which is O(n!∗n)O(n! * n) in the worst case.
  • Space complexity: O(n)O(n)

Where nn is the number of digits and kk is the 1-based rank of the permutation.


3. Recursion (Math)

class Solution:
    def getPermutation(self, n: int, k: int) -> str:
        fact = [1] * (n + 1)
        for i in range(1, n + 1):
            fact[i] = fact[i - 1] * i

        def build(digits, k):
            if not digits:
                return ""
            block = fact[len(digits) - 1]
            idx = (k - 1) // block
            d = digits.pop(idx)
            return d + build(digits, k - idx * block)

        return build([str(i) for i in range(1, n + 1)], k)

Time & Space Complexity

  • Time complexity: O(n2)O(n ^ 2)
  • Space complexity: O(n)O(n) for the recursion stack and the remaining digits.

Where nn is the number of digits.


4. Factorial Number System

class Solution:
    def getPermutation(self, n: int, k: int) -> str:
        fact = [1] * n
        for i in range(1, n):
            fact[i] = fact[i - 1] * i
        digits = [str(i) for i in range(1, n + 1)]
        k -= 1
        res = []
        for i in range(n - 1, -1, -1):
            idx = k // fact[i]
            k %= fact[i]
            res.append(digits.pop(idx))
        return "".join(res)

Time & Space Complexity

  • Time complexity: O(n2)O(n ^ 2)
  • Space complexity: O(n)O(n)

Where nn is the number of digits.