Number of Ways to Rearrange Sticks With K Sticks Visible Problem
Description
LeetCode Problem 1866.
There are n uniquely-sized sticks whose lengths are integers from 1 to n. You want to arrange the sticks such that exactly k sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it.
- For example, if the sticks are arranged
[1,3,2,5,4], then the sticks with lengths1,3, and5are visible from the left.
Given n and k, return the number of such arrangements. Since the answer may be large, return it modulo 10^9 + 7.
Example 1:
Input: n = 3, k = 2
Output: 3
Explanation: [1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.
The visible sticks are underlined.
Example 2:
Input: n = 5, k = 5
Output: 1
Explanation: [1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.
The visible sticks are underlined.
Example 3:
Input: n = 20, k = 11
Output: 647427950
Explanation: There are 647427950 (mod 10^9+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible.
Constraints:
1 <= n <= 10001 <= k <= n
Solution
Approach: Dynamic Programming
Let f[i][j] be the number of arrangements of i sticks (lengths 1 to i) where exactly j are visible from the left. Start from f[0][0] = 1; the answer is f[n][k].
Insert the shortest stick into an arrangement of the other i - 1 sticks:
- At the very front it is visible, and it does not hide anything, so the other sticks keep
j - 1visible ones:f[i - 1][j - 1]ways. - At any of the other
i - 1positions it stands behind a taller stick and is hidden, so the others keep alljvisible ones:(i - 1) * f[i - 1][j]ways.
So f[i][j] = f[i - 1][j - 1] + (i - 1) * f[i - 1][j], modulo 10^9 + 7.
Complexity: O(nk) time and O(nk) space.
class Solution:
def rearrangeSticks(self, n: int, k: int) -> int:
mod = 10**9 + 7
f = [[0] * (k + 1) for _ in range(n + 1)]
f[0][0] = 1
for i in range(1, n + 1):
for j in range(1, k + 1):
f[i][j] = (f[i - 1][j - 1] + f[i - 1][j] * (i - 1)) % mod
return f[n][k]