Number of Ways to Rearrange Sticks With K Sticks Visible - 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.

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 lengths 1, 3, and 5 are visible from the left.

Given n and k, return the number of such arrangements. Since the answer may be large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: n = 3, k = 2
Output: 3
💡 Note: The arrangements are [2,1,3], [2,3,1], [1,3,2]. In each case, exactly 2 sticks are visible from the left.
Example 2 — All Visible
$ Input: n = 5, k = 5
Output: 1
💡 Note: Only one arrangement has all 5 sticks visible: [1,2,3,4,5] in ascending order.
Example 3 — Only One Visible
$ Input: n = 4, k = 1
Output: 6
💡 Note: Arrangements where only the tallest stick (4) is visible: [4,3,2,1], [4,3,1,2], [4,2,3,1], [4,2,1,3], [4,1,3,2], [4,1,2,3].

Constraints

  • 1 ≤ n ≤ 1000
  • 1 ≤ k ≤ n

Visualization

Tap to expand
Stick Visibility Problem (n=4, k=2)Example Arrangements:Arrangement 1: [2,1,4,3] → 2 visible ✓2143Visible: 2, 4Arrangement 2: [3,2,1,4] → 2 visible ✓3214Visible: 3, 4Arrangement 3: [1,2,3,4] → 4 visible ✗1234Too many visibleCount arrangementswith exactly k=2 visibleKey: Green boxes are visible from leftA stick is visible if no taller stick is to its left
Understanding the Visualization
1
Input
n=4 sticks of lengths [1,2,3,4], want k=2 visible
2
Process
Try different arrangements and count visible sticks
3
Output
Count arrangements with exactly k visible sticks
Key Takeaway
🎯 Key Insight: The tallest stick is always visible - use DP to count arrangements by placing other sticks strategically
Asked in
Google 15 Facebook 8 Amazon 6
23.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen