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

Hiring now

Software engineer roles are open right now

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Senior Software Engineer -.NET

    Tyler Technologies · Annapolis, Maryland

  • Software Development Engineer II

    SaaS Labs · Bengaluru, Karnataka, India

  • Advanced Software Engineer - Product Architect (Legal, Safety, and Risk)

    Metropolitan Transportation Authority · New York, NY

Or practice this question first

Next question