LeetCode #60 Hard

Permutation Sequence

Permutation Sequence is LeetCode 60 (Hard). Write the numbers 1 to n in every possible order, sort those orderings like words in a dictionary, and number them from 1. Given n and k, return the ordering with number k, as a string of digits.

  • n is at most 9, so the digits are single characters and the largest count, 9! = 362,880, fits in an int.
  • k is always valid: between 1 and n!.

This page finds one ordering directly. Listing all of them is the job of Permutations.

Constraints
  • 1 <= n <= 9
  • 1 <= k <= n!
mathrecursion
Open on LeetCode ↗
02

Intuition

In dictionary order, the orderings come in blocks by their first digit. With 4 digits, all orderings starting with 1 come first, then all starting with 2, and so on, and each block holds 3! = 6 orderings, one for every way to arrange the other three digits.

So the first digit is just which block k lands in: divide by the block size. The position inside that block is the remainder, and it ranks an ordering of the remaining digits, which have the same block structure one size smaller. Repeat until no digits are left. Nothing is ever generated; each digit costs one division.

How to spot this pattern

You are asked for one item at a known position in a sorted list of arrangements, and the list is far too long to build. When the list splits into equal-sized groups by its first choice, the position can be decoded by division instead of enumeration.

03

Approach

Try it first

Before reading on: with digits 1 to 4, how many orderings start with 1? Using that, which digit must the 9th ordering start with? Aim for O(n²) time without generating any ordering.

1

Count from zero

Subtract 1 from k. With 0-based ranks, block b of size f covers ranks b·f to b·f + f - 1, so the block is exactly k // f. With 1-based k the last ordering of each block would divide into the next block.

2

Precompute the block sizes

Store fact[i] = i! for i from 0 to n - 1. When r digits remain, each of them leads a block of (r - 1)! orderings, so the loop reads fact from the largest entry down to 0! = 1.

3

Pick a digit, keep the remainder

Keep the unused digits in a sorted list. For each position, idx = k // fact[r - 1] is the block, so the digit is the idx-th unused one. Then k %= fact[r - 1] is the rank inside that block, which is the next problem to solve.

4

Remove the chosen digit

Delete it from the list so the next position only sees the digits still free. The list stays sorted after a deletion, which matters because block order follows digit order.

5

Why the blocks are equal

Fixing the first digit leaves r - 1 distinct digits, and every arrangement of them appears exactly once after it. Every first digit therefore gets (r - 1)! orderings, and dictionary order puts them side by side, smallest digit first. That equal size is the only fact the division relies on.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def getPermutation(self, n: int, k: int) -> str:
▶3 digits = [str(d) for d in range(1, n + 1)]
▶4 fact = [1] * n
▶5 for i in range(1, n):
▶6 fact[i] = fact[i - 1] * i
▶7 k -= 1
▶8 out = []
▶9 for r in range(n, 0, -1):
▶10 idx = k // fact[r - 1]
▶11 k %= fact[r - 1]
▶12 out.append(digits.pop(idx))
▶13 return "".join(out)
answerfree digits, in order1ranks 0–52ranks 6–113ranks 12–174ranks 18–23k is 9 (counting from 1)9korderings sorted like words4 digits: 24 orderings, 4 blocks of 6
free1 2 3 4
k9
Every ordering, laid out in order. Each block holds the orderings that start with one digit. All blocks are the same size, 3! = 6, because after fixing the first digit the other 3 can be arranged in 6 ways. The answer is wherever the marker falls, so nothing needs to be listed.
answerfree digits, in order1ranks 0–52ranks 6–113ranks 12–174ranks 18–23rank 88rank leftcount from zero: rank 8
k8was 9
Shift to ranks starting at 0. Then block number is a plain division: ranks 0 to 5 are block 0, the next 6 are block 1, and so on. With counting from 1, the last ordering of each block would divide into the next block.
answerfree digits, in order1ranks 0–52ranks 6–113ranks 12–174ranks 18–23rank 88rank=1block×6block size+2rank insiderank 8 is in block 1: digit 2
block size63!
block1
rank inside2
4 free digits, blocks of 6. 8 divided by 6 is 1 with 2 left over, so rank 8 lies in block 1, the one led by digit 2. Every ordering in that block starts with 2, so 2 is the next digit for sure.
answer2free digits, in order1ranks 0–13ranks 2–34ranks 4–5rank 22rank leftorderings of the 3 free digits2 placed, rank 2 among the rest
answer2
free1 3 4
k2
Zoom into that block. Inside it, the orderings are 2 followed by every ordering of 1, 3, 4, in order. So the leftover 2 is a rank among orderings of those 3 digits: the same question, one digit smaller.
answer2free digits, in order1ranks 0–13ranks 2–34ranks 4–5rank 22rank=1block×2block size+0rank insiderank 2 is in block 1: digit 3
block size22!
block1
rank inside0
3 free digits, blocks of 2. 2 divided by 2 is 1 with 0 left over, so rank 2 lies in block 1, the one led by digit 3. Every ordering in that block starts with 3, so 3 is the next digit for sure.
answer23free digits, in order1rank 04rank 1rank 00rank leftorderings of the 2 free digits3 placed, rank 0 among the rest
answer23
free1 4
k0
Zoom into that block. Inside it, the orderings are 3 followed by every ordering of 1, 4, in order. So the leftover 0 is a rank among orderings of those 2 digits: the same question, one digit smaller.
answer23free digits, in order1rank 04rank 1rank 00rank=0block×1block size+0rank insiderank 0 is in block 0: digit 1
block size11!
block0
rank inside0
2 free digits, blocks of 1. 0 divided by 1 is 0 with 0 left over, so rank 0 lies in block 0, the one led by digit 1. Every ordering in that block starts with 1, so 1 is the next digit for sure.
answer231free digits, in order4rank 0rank 00rank leftorderings of the 1 free digit1 placed, rank 0 among the rest
answer231
free4
k0
Zoom into that block. Inside it, the orderings are 1 followed by every ordering of 4, in order. So the leftover 0 is a rank among orderings of those 1 digit: the same question, one digit smaller.
answer231free digits, in order4rank 0rank 00rank=0block×1block size+0rank insiderank 0 is in block 0: digit 4
block size10!
block0
rank inside0
1 free digit, blocks of 1. 0 divided by 1 is 0 with 0 left over, so rank 0 lies in block 0, the one led by digit 4. It is the only digit left, so it goes last.
answer2314free digits, in orderno digits left0rank left4 placed, no digits left
answer2314
freenone
k0
All 4 positions are filled. Each digit was fixed by one division, without visiting any other ordering.
answer2314free digits, in orderno digits left0rank leftnothing left to skipanswer: 2314
return"2314"
Return 2314. 4 divisions replaced listing up to 24 orderings.
05

Common pitfalls

Dividing the 1-based k

✗ Wrong
idx = k // fact[r - 1]   # k not decremented
✓ Right
k -= 1
...
idx = k // fact[r - 1]

For n = 3, k = 2 the answer is "132". Without the decrement, 2 // 2 = 1 picks digit 2 first and returns "213". The last ordering of every block has a 1-based rank that is a multiple of the block size, so it always spills into the next block.

Picking the digit by value, not by position in the unused list

✗ Wrong
out.append(str(idx + 1))
✓ Right
out.append(digits.pop(idx))

idx counts blocks among the digits that are still free. Once 2 is used, block 1 belongs to digit 3, not 2. For n = 3, k = 4 the value version returns "221" instead of "231".

06

Edge cases

k = 1

Every division gives 0, so each step takes the smallest free digit and the answer is 1 2 … n in order.

k = n!

After the decrement k = n! - 1, every division picks the largest free digit, giving n … 2 1.

n = 1

One pass with block size 0! = 1 picks the only digit, "1".

07

Complexity

Time
O(n²)
Space
O(n)
There are n positions, and each removes one digit from a list of at most n, which shifts the rest. With n ≤ 9 that is at most 45 shifts. Space is the digit list, the factorials and the answer.
08

Permutation Sequence FAQ

What is the factorial number system?

It writes a number with place values 0!, 1!, 2!, … instead of powers of ten, where the digit in the i! place is at most i. Writing k - 1 this way gives the Lehmer code of the kth ordering: each digit says how many smaller free digits were skipped at that position. The loop above produces those digits one by one with // and %.

How do you go the other way and find the rank of a given permutation?

Reverse the loop. For each position, count the free digits smaller than the one placed there, multiply that count by the block size for that position, and add it up. Add 1 at the end for a 1-based rank. For "231": digit 1 is free and smaller than 2, giving 1 × 2! = 2; then 1 is still free and smaller than 3, giving 1 × 1! = 1. The total is 3, so "231" is ordering number 4.

Why not reach the kth permutation by calling next permutation k - 1 times?

It is correct but costs O(k · n), and k can be 9! = 362,880. The block division reaches the answer in n steps however large k is. Next Permutation is the right tool when you need the orderings one after another, not one far ahead.