Problem Description
(A short summary or question text)
Given n uniquely-sized sticks with lengths 1 through n, the task is to count the number of arrangements such that exactly k sticks are visible from the left. A stick is visible if there is no longer stick to its left. Return the answer modulo 10^9 + 7.
Key Insights
- A stick is visible if it is the tallest up to that point in the arrangement.
- The largest stick (length n) is always visible if placed at the front.
- If the largest stick is placed as leftmost visible stick, then the remaining n - 1 sticks need to be arranged to have exactly k - 1 visible sticks.
- If the largest stick is inserted in any other position, it will be hidden, and the subproblem remains with n - 1 sticks and k visible sticks.
- This leads to the recurrence: dp[n][k] = dp[n - 1][k - 1] + (n - 1) * dp[n - 1][k].
Space and Time Complexity
Time Complexity: O(n * k) because each state dp[i][j] for i in 1..n and j in 1..k is computed. Space Complexity: O(n * k) due to the 2D DP table used to store subproblem solutions.
Solution
We use dynamic programming with a 2D table dp, where dp[i][j] represents the number of arrangements using i sticks with exactly j sticks visible from the left. The main recurrence is:
- dp[i][j] = dp[i - 1][j - 1] when the ith stick (largest among those considered) is placed so that it's visible.
- dp[i][j] += (i - 1) * dp[i - 1][j] when the largest stick is inserted into any position where it is not visible. A modulus operation at each step ensures that numbers remain manageable and meet the problem requirements.