Write the digits 1 to n in every possible order and sort those orderings from smallest to largest. For n = 3 there are six orderings, running from 123 up to 321.
Given n and a position k (counting from 1), return the ordering at position k as a string.
Example 1
Input: n = 4, k = 14 Output: "3142" Why: orderings 13 to 18 start with 3; 3124 is 13th, 3142 is 14th
2 more examples and the constraints
Example 2
Input: n = 3, k = 5 Output: "312" Why: 123, 132, 213, 231, then 312
Example 3
Input: n = 1, k = 1 Output: "1" Why: a single digit has one ordering
Constraints
- 1 ≤ n ≤ 9
- 1 ≤ k ≤ n! (so k ≤ 362,880)
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Step k − 1 timesO(k · n)
- Pick each digit by countingO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 9, k = 362,880 | Verdict |
|---|---|---|---|
| Step k − 1 times | O(k · n) | Passes at n = 9; misses the point | |
| Pick each digit by counting | O(n²) | Best; nine divisions |
n = how many digits, k = the position wanted (up to n!).
Edge cases to test
- k = 1. The answer is the digits in increasing order, "123...n".
- k = n!. The answer is the digits in decreasing order; this is where forgetting
k -= 1runs off the end. - n = 1. Only k = 1 is possible and the answer is "1".
- Largest input. n = 9 needs 8! = 40,320 as the first block; it fits easily in an int.
Common mistakes
- Dividing k before subtracting 1, so the last ordering in each run picks the next digit.
- Picking by digit value instead of by index among the digits still unused.
- Dividing the block by the wrong count, or dividing by 0 after the last digit.
How to talk through it
- 1Clarify. Is k counted from 1? Is k always at most n!? Should the answer be a string?
- 2Give the brute force. Start at 1 2 ... n and apply next permutation k − 1 times; say it is O(k · n), up to 360,000 moves.
- 3Spot the runs. Each first digit leads (n − 1)! orderings, so k ÷ (n − 1)! names it without building anything.
- 4Code the counting. Subtract 1 from k, then divide and take the remainder once per digit, removing used digits from a list.
- 5Test out loud. Run k = 1, k = n! and n = 1, and walk n = 4, k = 14 to get 3142.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?