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
Rearrange Sticks With K Visible INPUT n=3 sticks (lengths 1,2,3) 1 2 3 View n = 3 k = 2 (visible) Find arrangements with exactly k=2 visible from the left ALGORITHM STEPS 1 Define DP State dp[i][j] = ways with i sticks, j visible from left 2 Base Case dp[1][1] = 1 (one stick, one visible) 3 Recurrence Tallest at left: dp[i-1][j-1] Not at left: (i-1)*dp[i-1][j] 4 Build DP Table Fill table bottom-up i\j 1 2 3 1 1 0 0 2 1 1 0 3 2 3 1 ans FINAL RESULT 3 Valid Arrangements: [1,3,2] Visible: 1, 3 [2,1,3] Visible: 2, 3 [2,3,1] Visible: 2, 3 Output: 3 dp[3][2] = 3 Key Insight: When placing the tallest stick (n) at position 1, it's always visible from left: contributes dp[n-1][k-1]. When tallest is at positions 2 to n, it blocks everything behind it. We have (n-1) choices for these positions, each contributing dp[n-1][k]. Total: dp[n][k] = dp[n-1][k-1] + (n-1) * dp[n-1][k] TutorialsPoint - Number of Ways to Rearrange Sticks With K Sticks Visible | DP Approach
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