Number of Ways to Rearrange Sticks With K Sticks Visible - Problem
Imagine you have n uniquely-sized sticks with lengths from 1 to n (like a set of measuring sticks). Your challenge is to arrange them in a row such that exactly k sticks are visible when looking from the left.
A stick is visible from the left if there are no taller sticks standing to its left. Think of it like a skyline - you can only see buildings that aren't blocked by taller ones in front of them.
Example: If sticks are arranged as [1,3,2,5,4], then:
- Stick 1 is visible (nothing blocks it)
- Stick 3 is visible (only shorter stick 1 is to its left)
- Stick 2 is not visible (taller stick 3 blocks it)
- Stick 5 is visible (tallest so far)
- Stick 4 is not visible (taller stick 5 blocks it)
So 3 sticks are visible from the left. Given n and k, return the number of arrangements where exactly k sticks are visible. Since the answer can be huge, return it modulo 109 + 7.
Input & Output
example_1.py โ Basic case
$
Input:
n = 3, k = 2
โบ
Output:
3
๐ก Note:
There are 3 arrangements where exactly 2 sticks are visible: [2,1,3], [2,3,1], and [1,2,3]. In each case, exactly 2 sticks can be seen from the left.
example_2.py โ Edge case k=1
$
Input:
n = 5, k = 1
โบ
Output:
24
๐ก Note:
Only arrangements starting with stick 5 (tallest) have exactly 1 visible stick. There are 4! = 24 ways to arrange the remaining 4 sticks after placing 5 first.
example_3.py โ All visible
$
Input:
n = 4, k = 4
โบ
Output:
1
๐ก Note:
Only the arrangement [1,2,3,4] has all 4 sticks visible from the left, since each stick is taller than all previous ones.
Constraints
- 1 โค n โค 1000
- 0 โค k โค n
- Answer fits in 32-bit integer after taking modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Tallest building insight
The tallest building (n) is always visible regardless of position
2
Two placement choices
Place building n as the k-th visible, or place it where it doesn't affect the count
3
Recursive subproblems
If n is k-th visible: solve for (n-1, k-1). If n doesn't affect count: (i-1) ways to place n among i-1 positions times solutions for (n-1, k)
4
Combine solutions
Total arrangements = dp[n-1][k-1] + (n-1) ร dp[n-1][k]
Key Takeaway
๐ฏ Key Insight: The tallest element is always visible, so we can recursively build solutions by deciding whether to make it the k-th visible element or place it in a non-affecting position.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code