Number of Ways to Rearrange Sticks With K Sticks Visible — LeetCode 1866 Python Solution
- Problem
- #1866
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- 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.
Python solution
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]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times k) |
| Space | O(n \times k) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1866. Number of Ways to Rearrange Sticks With K Sticks Visible is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1866. Number of Ways to Rearrange Sticks With K Sticks Visible?
- LeetCode 1866. Number of Ways to Rearrange Sticks With K Sticks Visible is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1866. Number of Ways to Rearrange Sticks With K Sticks Visible?
- The Python solution on this page runs in O(n \times k).
- What is the space complexity of LeetCode 1866. Number of Ways to Rearrange Sticks With K Sticks Visible?
- The Python solution on this page uses O(n \times k) auxiliary space.
- What topics does LeetCode 1866. Number of Ways to Rearrange Sticks With K Sticks Visible cover?
- LeetCode 1866. Number of Ways to Rearrange Sticks With K Sticks Visible is tagged Math, Dynamic Programming and Combinatorics on LeetCode.