Permutation Sequence

Asked atInfoEdge India Ltd
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given two integers n and k, return the k-th permutation sequence of the numbers [1, 2, 3, ..., n].

The permutations are arranged in lexicographic order (i.e., dictionary order).

You must solve the problem without generating all permutations explicitly.

Input: n = 3, k = 3 **Output: **"213" Explanation: The permutations in order are:

    1. 123
    1. 132
    1. 213 ← K = 3
    1. 231
    1. 312
    1. 321

**Input: **n = 3, k = 5 Output: "312" **Explanation: **K = 5 corresponds to the fifth permutation in lexicographic order.

Input: n = 4, k = 9

  • 1 <= n <= 9
  • 1 <= k <= n! (i.e., k is always a valid permutation index)

cpp

class Solution {
public:
    string getPermutation(int n, int k) {
        // Your code goes here
    }
};

java

class Solution {
    public String getPermutation(int n, int k) {
        // Your code goes here
    }
}

python

class Solution:
    def getPermutation(self, n: int, k: int) -> str:
        # Your code goes here

javascript

class Solution {
    getPermutation(n, k) {
        // Your code goes here
    }
}

csharp

class Solution {
    public string GetPermutation(int n, int k) {
        // Your code goes here
    }
}

go

func getPermutation(n int, k int) string {
    // Your code goes here
}
Stuck? Show a way to structure it+
  1. 01Convert one-based k to zero-based k minus one.
  2. 02Keep sorted unused digits and precompute factorials.
  3. 03At each remaining length m, choose index k divided by factorial(m minus one).
  4. 04Remove that digit and replace k with the remainder.
  5. 05Append until no digits remain.

Reference answer

Then expect these follow-ups

  • How would you find the rank of a given permutation?

    Tests: follow-up reasoning

  • How does this change when digits can repeat?

    Tests: constraint adaptation

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question