We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Number of Ways to Rearrange Sticks With K Sticks Visible

Difficulty: Hard


Problem Description

Given n uniquely-sized sticks whose lengths are integers from 1 to n, arrange them such that exactly k sticks are visible from the left. A stick is visible from the left if there are no longer sticks to its left. Return the number of such arrangements modulo 10^9 + 7.


Key Insights

  • A stick is visible if it is the tallest among all sticks to its left.
  • The problem can be formulated using combinatorial mathematics.
  • The number of ways to choose which k sticks are visible can be calculated using combinations.
  • The remaining sticks can be arranged in any order behind the visible ones.
  • Dynamic programming can be employed for efficient computation of the arrangements.

Space and Time Complexity

Time Complexity: O(n^2)
Space Complexity: O(n)


Solution

The solution involves a dynamic programming approach where we maintain a table to compute the number of valid arrangements. We define dp[i][j] as the number of ways to arrange i sticks such that exactly j are visible.

  1. Initialize dp[1][1] to 1 since there's only one way to arrange one stick.
  2. For each number of sticks from 2 to n, and for each possible number of visible sticks from 1 to min(k, i), update the dp table based on the previous counts.
  3. The final answer will be stored in dp[n][k], which represents the arrangements of n sticks with exactly k visible.

Code Solutions

MOD = 10**9 + 7

def rearrangeSticks(n, k):
    dp = [[0] * (k + 1) for _ in range(n + 1)]
    dp[0][0] = 1  # Base case: 0 sticks with 0 visible

    for i in range(1, n + 1):
        for j in range(1, min(k, i) + 1):
            # Add the case where the current stick is visible
            dp[i][j] = dp[i - 1][j - 1] % MOD
            # Add the case where the current stick is not visible
            dp[i][j] += (dp[i - 1][j] * (i - 1)) % MOD
            dp[i][j] %= MOD

    return dp[n][k]

# Example usage:
# print(rearrangeSticks(3, 2))  # Output: 3
← Back to All Questions