KatInterview

Count Grid Walkways Without Three Consecutive Steps

Dynamic ProgrammingAuto-graded · 21 test cases
MediumAuto-gradedDynamic Programmingdynamic-programminggridcombinatorics

Last updated

Count valid grid paths composed of horizontal and vertical steps such that no direction is repeated three times in a row.

You are navigating a 2D grid from the origin (0, 0) to the destination (right_moves, up_moves). Each move must be either one step to the right (R) or one step upward (U).

A path is considered valid if it never contains three consecutive identical moves (that is, neither RRR nor UUU appears anywhere in the path sequence).

Write a function count_grid_paths(right_moves: int, up_moves: int) -> int that calculates the total number of distinct valid paths from (0, 0) to (right_moves, up_moves).

Rules & Edge Cases

  • If either right_moves or up_moves is negative, return 0.
  • If both right_moves and up_moves are 0, return 1 (the empty path is valid).
  • A path consisting of only one step direction is valid up to 2 steps (e.g., (2, 0) returns 1), but invalid for 3 or more steps (e.g., (3, 0) returns 0).

Constraints

  • -100 <= right_moves <= 200
  • -100 <= up_moves <= 200

Examples

Example 1

Input: count_grid_paths(2, 2)

Output: 6

Example 2

Input: count_grid_paths(3, 1)

Output: 2

Example 3

Input: count_grid_paths(0, 2)

Output: 1

Hints

Hint 1

Standard grid DP tracks path counts at cell (i, j), but here the next move depends on recent moves. Consider adding state tracking for the last direction taken and its current streak length.

Hint 2

Since a streak cannot reach 3, the current streak length of the last move can only be 1 or 2. How many total state variables per cell does this require?

Hint 3

An 'R' step from (i-1, j) can transition from any state at (i-1, j) ending in a 'U' streak (giving streak length 1), or from a state ending in 'R' with streak length 1 (giving streak length 2).