Program to count number of ways ball can drop to lowest level by avoiding blacklisted steps in Python

Suppose we have a value h and a list of numbers called blacklist. We are currently at height h, and are playing a game to move a small ball down to height 0. Now, in even rounds (starting from 0) we can move the ball 1, 2, or 4 stairs down. And in odd rounds, we can move the ball 1, 3, or 4 stairs down. Some levels are blacklisted. So if the ball reach there, it will die immediately. We have to find the number of ways the ball can move down at height 0. If the answer is too large, then mod the result by 10^9 + 7.

So, if the input is like h = 5 blacklist = [2, 1], then the output will be 2, because on round 0, move one step first (5 to 4), then in the next round from 4 to 0. Another possible way could be at round 0, move two steps (5 to 3), then in the next round 3 to 0.

Solution Approach

We'll use dynamic programming where dp[i][0] represents ways to reach height i in an even round and dp[i][1] represents ways to reach height i in an odd round. The key insight is that available moves alternate between rounds.

Algorithm Steps

  • Convert blacklist to a set for O(1) lookup
  • If starting position or target is blacklisted, return 0
  • Initialize dp array with base case
  • For each height, calculate ways from previous positions
  • Return ways to reach target in even round

Implementation

def solve(h, blacklist):
    blacklist = set(blacklist)
    if 0 in blacklist or h in blacklist:
        return 0
    
    dp = [[0, 0] for i in range(h + 1)]
    dp[0] = [1, 1]
    m = 10 ** 9 + 7
    
    for i in range(1, h + 1):
        for x in [1, 2, 3, 4]:
            if i - x >= 0 and i - x not in blacklist:
                if x != 3:  # Move 3 not allowed in even rounds
                    dp[i][0] += dp[i - x][1]
                if x != 2:  # Move 2 not allowed in odd rounds
                    dp[i][1] += dp[i - x][0]
        dp[i][0] %= m
        dp[i][1] %= m
    
    return dp[h][0]

# Test with given example
h = 5
blacklist = [2, 1]
print(solve(h, blacklist))
2

How It Works

The algorithm builds solutions bottom-up:

  • Even rounds (0, 2, 4...): Can move 1, 2, or 4 steps down
  • Odd rounds (1, 3, 5...): Can move 1, 3, or 4 steps down
  • DP state: dp[i][j] = ways to reach height i in round type j
  • Transitions: Add ways from valid previous positions

Example Walkthrough

For h = 5, blacklist = [2, 1]:

  • Round 0 (even): From 5, can go to 4 (move 1) or 3 (move 2)
  • Round 1 (odd): From 4, can go to 0 (move 4); From 3, can go to 0 (move 3)
  • Total valid paths: 5?4?0 and 5?3?0 = 2 ways

Conclusion

This dynamic programming solution efficiently counts valid paths by tracking round parity and avoiding blacklisted positions. The time complexity is O(h) and space complexity is O(h).

Updated on: 2026-03-26T17:06:03+05:30

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements