permutation sequence

Permutation Sequence Made Easy: Formula, Examples, and Code Explained

By Matthew Smith
AD

If you have ever stared at a list of every possible ordering of the numbers one through n and wondered how to jump straight to the millionth arrangement without generating the other 999,999, you have already met the permutation sequence problem. It is one of those deceptively simple challenges that separates programmers who reach for brute force from those who reach for mathematics. The task looks modest on the surface, yet it quietly teaches the factorial number system, index arithmetic, and the value of thinking carefully before typing.

Whether you are grinding through coding interview prep, building a scheduling engine, or simply curious about combinatorics, knowing how to compute the kth permutation directly is a genuinely useful skill. This guide walks through the problem statement, the number theory underneath it, a step-by-step algorithm, the mistakes that trip people up, and the places where this technique quietly powers real software.

Understanding the Permutation Sequence Problem

At its core, the permutation sequence problem asks a single question: given the set of integers from 1 to n, arranged in lexicographic order, what is the kth permutation? For example, with n equal to 3, the orderings are 123, 132, 213, 231, 312, and 321. Ask for the fourth one and the answer is 231. Ask for the sixth and you get 321. Nothing about the request is ambiguous, which is exactly what makes it a favorite in technical interviews.

AD
a black background with yellow lines and numbers on the bottom right hand corner, which is labeled permutation
a black background with yellow lines and numbers on the bottom right hand corner, which is labeled permutation
Permutation & Combination (P&C) Short Notes | Class 11 Maths | JEE Mains
Permutation & Combination (P&C) Short Notes | Class 11 Maths | JEE Mains
a paper with some writing on it that says permutation and combination in red
a paper with some writing on it that says permutation and combination in red

The catch is scale. The number of permutations grows factorially, so n equal to 9 already produces 362,880 arrangements, and n equal to 12 crosses 479 million. Any approach that materializes the full list collapses under that growth curve. The interesting part of the problem is not producing permutations at all, but understanding the internal structure that lets you index into them directly.

What the Problem Actually Asks

Formally, you receive two integers, n and k, and must return the kth permutation sequence of the digits 1 through n, using 1-based counting. The result is typically returned as a string of digits rather than a numeric value, because leading digits matter and n can grow large enough to overflow standard integer types. This detail matters more than it first appears.

Counting
Counting
Pulsations by Liam Hennessy
Pulsations by Liam Hennessy
Permutation Testing: Distribution-Free Significance Assessment → Nonparametric Test
Permutation Testing: Distribution-Free Significance Assessment → Nonparametric Test

Constraints vary by source, but the popular version of this challenge on LeetCode caps n at 9 specifically so that the total number of permutations fits inside a signed 32-bit integer. Other variants push n higher, which forces you to handle large arithmetic carefully. Either way, the requested output is a deterministic string, and the algorithm must produce it without enumerating intermediate results.

Why Generating Everything Is a Trap

The naive solution is straightforward: recursively generate every permutation in lexicographic order, count them, and stop when the counter reaches k. This works beautifully for small inputs and is genuinely fine if n stays below roughly 8. Beyond that, both time and memory explode, and the program becomes unusable rather than merely slow.

AD

Consider what happens with n equal to 12. The recursion tree has 479 million leaves, and even if each leaf costs only a few nanoseconds, you are looking at seconds to minutes of runtime along with a mountain of allocations. The direct construction method described later runs in quadratic time with no recursion at all, which is a difference measured in orders of magnitude rather than constant factors.

Permutation Sequence in Python
Permutation Sequence in Python
Permutation Calculator
Permutation Calculator
Permutation Formula Explained | Easy Combinatorics & Probability Guide
Permutation Formula Explained | Easy Combinatorics & Probability Guide
a poster with instructions on how to use the formulas for permutions and master sheet
a poster with instructions on how to use the formulas for permutions and master sheet
Permutations and Combinations Worksheet Answers Elegant Permutations and Binations Worksheet Answer Key
Permutations and Combinations Worksheet Answers Elegant Permutations and Binations Worksheet Answer Key
a poster with instructions on how to use permutions and combinations
a poster with instructions on how to use permutions and combinations

The Mathematics Behind the kth Permutation

Every lexicographic ordering of a set has a hidden structure, and that structure is built from factorials. When you fix the first digit of a permutation, the remaining digits can be arranged in (n minus 1) factorial ways. That single observation converts the problem from searching a list into performing division and taking remainders.

Think of the sorted list of candidate digits as a sequence of blocks. The first block contains all permutations starting with the smallest digit, the second block contains all permutations starting with the next digit, and so on. Each block has exactly the same size, which means you can locate the correct block with a single integer division and then repeat the process on a smaller set.

AD

Factorials as Block Sizes

The size of each block depends entirely on how many digits remain to be placed. With n digits total, fixing the first digit leaves a block of (n minus 1) factorial permutations. Fixing the second leaves (n minus 2) factorial, and the pattern continues down to 1 factorial, which equals one. These block sizes are what make the greedy digit-by-digit construction correct.

an array of different colored balls on a white background
an array of different colored balls on a white background
the formula for permutions and combinations worksheet with answers on how to use them
the formula for permutions and combinations worksheet with answers on how to use them
File:Permutations with repetition.svg - Wikimedia Commons
File:Permutations with repetition.svg - Wikimedia Commons
Sequence & Series Class 11 NCERT | Complete AP & GP Formula Sheet for JEE
Sequence & Series Class 11 NCERT | Complete AP & GP Formula Sheet for JEE

Having the factorials precomputed in a small table makes the implementation cleaner and faster, since you avoid recalculating the same values repeatedly. For reference, here are the values you will typically need:

n(n-1)!Total permutations n!
111
212
326
4624
524120
6120720
77205,040
85,04040,320
940,320362,880

Translating k Into Digits

The conversion process is a sequential division routine, closely related to the factorial number system. Start by subtracting one from k so that counting begins at zero internally. Divide that value by (n minus 1) factorial, and the quotient tells you which element of the sorted candidate list becomes the first digit. The remainder becomes the new k for the next round.

AD

Repeat with the remaining candidates and the next smaller factorial until no digits are left. Each step consumes one choice and shrinks the problem, which is why the whole procedure finishes in a number of iterations equal to n. The quotient always falls within the range of available indices, so no bounds checking beyond basic sanity validation is required.

Building the Algorithm Step by Step

A clean implementation needs only three ingredients: a mutable list of available digits, a table of factorials from zero up to n, and a loop that runs exactly n times. The loop computes an index, extracts the corresponding digit, removes it from the pool, and appends it to the result. That is the entire algorithm in essence.

Choosing the right data structure for the pool matters if you care about squeezing out constant factors. A plain dynamic array or list works fine and keeps the code readable, since removal from the middle costs linear time but n is small. A balanced binary search tree or a Fenwick tree would reduce the per-removal cost for very large n, though such optimizations are rarely needed in practice.

Walking Through a Concrete Example

Take n equal to 4 and k equal to 9, which asks for the ninth permutation of 1234. Subtract one to get 8. The candidates are 1, 2, 3, and 4, and the block size is 3 factorial, which is 6. Dividing 8 by 6 gives a quotient of 1 and a remainder of 2, so the first digit is the element at index 1, namely 2.

The pool is now 1, 3, 4 with k equal to 2. The next block size is 2 factorial, which is 2. Dividing 2 by 2 gives quotient 1 and remainder 0, so the second digit is 3. The pool becomes 1 and 4 with k equal to 0. The next block size is 1 factorial, which is 1, so the quotient is 0 and the third digit is 1. The last digit is whatever remains, which is 4. The assembled answer is 2314, matching the ninth entry in the lexicographic list.

Complexity, Data Structures, and Micro-Optimizations

Time complexity is O(n squared) with a simple list, because each of the n iterations performs an O(n) removal. Space complexity is O(n) for the candidate pool and the output buffer, plus O(n) for the factorial table. If you replace the list with a Fenwick tree over digit positions, the removals and kth-element queries both drop to O(log n), giving an overall O(n log n) bound.

Practical micro-optimizations include precomputing factorials once, using a StringBuilder or equivalent in languages where string concatenation is expensive, and avoiding repeated modulo operations on large numbers. In languages with fixed-width integers, watch for overflow when n grows past 20, since 21 factorial exceeds the range of a 64-bit unsigned integer. Big-integer libraries or careful early termination solve that problem cleanly.

Edge Cases, Pitfalls, and Practical Uses

Most bugs in permutation sequence implementations come from indexing conventions rather than from the math itself. Mixing 0-based and 1-based counting, forgetting to decrement k before the first division, or failing to shrink the factorial index correctly will each produce plausible-looking but wrong output. Writing a couple of small brute-force comparisons during development catches all of these quickly.

Boundary inputs deserve explicit testing as well. When n equals 1, k must equal 1 and the answer is simply that single digit. When k equals n factorial, you should receive the fully reversed sequence. Undefined values, such as k larger than the total permutation count or k less than one, should ideally be rejected rather than silently returning garbage.

Off-by-One Errors and Overflow

The classic off-by-one trap is forgetting that k is 1-based while array indices are 0-based. Decrementing k at the start of the algorithm aligns the two, and every subsequent remainder stays consistent with the candidate pool indices. Skipping that step shifts the entire result by one permutation, which is often close enough to look correct at a glance during debugging.

Overflow is the second common failure mode. Factorials grow explosively, and even when the final answer fits in a 32-bit or 64-bit integer, intermediate products may not. Languages such as Python sidestep this with arbitrary-precision integers, while C, C++, and Java require either a wider type, a saturation strategy, or a big-integer class depending on the constraint envelope.

Where Permutation Sequences Show Up in the Wild

Ranking and unranking permutations is a fundamental operation in combinatorial generation, and it appears in randomized testing frameworks, load balancing schemes, and search-space traversal. Any system that needs to sample a specific arrangement without enumerating all predecessors benefits from the same indexing trick used here.

Cryptographic and security-adjacent code sometimes uses permutation indexing for key scheduling and shuffle verification, where reproducing a specific shuffle from a seed and index must be deterministic. Database query planners also borrow the concept when ordering join strategies, and puzzle solvers use it to jump to a particular state in a permutation graph rather than exploring from the start.

Take the factorial-block technique and try it on a variant, such as finding the kth permutation of a string with repeated characters or the kth combination rather than arrangement. Each variation bends the same core idea in a slightly different direction, and working through them will sharpen your intuition for combinatorial indexing far more than memorizing a single solution ever could.

AD