#1866
Number of Ways to Rearrange Sticks With K Sticks Visible
HardMathDynamic ProgrammingCombinatoricsDynamic ProgrammingCombinatorics
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n * k) |
| Space | O(n) | O(n * k) |
💡
Intuition
Time O(n * k)Space O(n * k)
The optimal solution uses dynamic programming to build the number of arrangements based on previously computed values. It leverages combinatorial principles to efficiently calculate the number of ways to arrange sticks with exactly k visible.
⚙️
Algorithm
5 steps- 1Step 1: Create a DP table dp[i][j] where dp[i][j] represents the number of ways to arrange i sticks with exactly j visible.
- 2Step 2: Initialize base cases: dp[0][0] = 1 (0 sticks, 0 visible).
- 3Step 3: Use the relation: dp[i][j] = dp[i-1][j-1] * (i - 1) + dp[i-1][j] * (i - 1), where the first term accounts for placing the longest stick visible and the second for not placing it.
- 4Step 4: Iterate through the DP table to fill it up to dp[n][k].
- 5Step 5: Return dp[n][k] modulo 10^9 + 7.
solution.py8 lines
1def count_visible_sticks(n, k):
2 MOD = 10**9 + 7
3 dp = [[0] * (k + 1) for _ in range(n + 1)]
4 dp[0][0] = 1
5 for i in range(1, n + 1):
6 for j in range(1, min(k, i) + 1):
7 dp[i][j] = (dp[i - 1][j - 1] * (i - 1) + dp[i - 1][j] * (i - 1)) % MOD
8 return dp[n][k]ℹ
Complexity note: The complexity is O(n * k) due to the nested loops filling the DP table, which is efficient compared to the brute force approach.
- 1The number of visible sticks is determined by the placement of the longest stick.
- 2Dynamic programming allows us to build solutions incrementally based on smaller subproblems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.