1794. Kth Pick of K

Medium3.5 points estimatedCombinatoricsEnumerationMaths

A lottery draws size different balls out of balls numbered 1 to n. Write every possible draw as an ascending list of ball numbers and put all the lists in lexicographic order, so [1,2,3] comes before [1,2,4], which comes before [1,3,4]. The lists are far too many to write down, yet the organisers want the one at position rank, counting from 1.

Return that draw as an ascending int[] of length size. The rank is always valid, 1 <= rank <= C(n, size), and every draw is a different set, so the answer is unique. Do not enumerate: for each next ball, count the draws that start with it as C(balls left after it, balls still needed - 1), skip that whole block when the rank exceeds it and subtract the block from the rank. Counts can reach about 1.3 * 10^14, so use 64-bit arithmetic. Time is O(n^2) to build the binomial table, space O(n^2).

Example 1

Input:
n = 5, size = 3, rank = 1
Output:
[1,2,3]
Explanation:

The first draw in lexicographic order is the three smallest balls.

Example 2

Input:
n = 5, size = 3, rank = 10
Output:
[3,4,5]
Explanation:

There are C(5,3) = 10 draws and the last one is the three largest balls.

Example 3

Input:
n = 6, size = 2, rank = 7
Output:
[2,4]
Explanation:

Five draws start with ball 1, then [2,3] is sixth and [2,4] is seventh.

Constraints

1 ≤ size ≤ n ≤ 50

1 ≤ rank ≤ C(n, size) ≤ 1.3 * 1014

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n^2)
Space
O(n^2)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…