KatInterview

Count Lattice Paths Through Required Checkpoints

Math & Bit ManipulationAuto-graded · 18 test cases
MediumAuto-gradedMath & Bit Manipulationcombinatoricsmathdynamic programming

Last updated

Tests whether a candidate can combine combinatorics (binomial coefficients) to count grid paths that must pass through a sequence of ordered checkpoints.

Count Lattice Paths Through Required Checkpoints

You are navigating an infinite 2-D grid, starting at the origin (0, 0). At each step you may move right (R) or up (U) — never left or down.

You are given a list of checkpoints: grid coordinates that your path must visit, in the order they are listed. The checkpoints are guaranteed to be reachable in order (each checkpoint is strictly to the right or above — or both — of the previous one, and the origin is implicitly the zeroth checkpoint).

Count the number of distinct monotone lattice paths from (0, 0) to the last checkpoint that pass through every checkpoint in the given order.

Because the answer can be very large, return it modulo 10^9 + 7.

How paths are counted

A monotone lattice path from point A = (r1, c1) to point B = (r2, c2) (with r2 >= r1 and c2 >= c1) consists of exactly (r2 - r1) + (c2 - c1) steps, of which (r2 - r1) are R-steps and (c2 - c1) are U-steps. The number of such paths is the binomial coefficient C(dx + dy, dx) where dx = r2 - r1 and dy = c2 - c1.

Because the checkpoints must be visited in order, the total count is the product of the path counts between consecutive checkpoints (including from the origin to the first checkpoint and from the last checkpoint to itself, which is trivially 1).

Input

  • checkpoints: a list of [x, y] pairs (non-empty), representing the required waypoints in order. The last checkpoint is the destination.
  • The path always starts at (0, 0).

Constraints

  • 1 <= len(checkpoints) <= 50
  • 0 <= x, y <= 1000 for every checkpoint [x, y]
  • Checkpoints are given in strictly increasing order: for consecutive checkpoints [x1, y1] and [x2, y2], it holds that x2 >= x1 and y2 >= y1 (with at least one strict inequality), and the first checkpoint satisfies x >= 0, y >= 0 (not both zero unless the only checkpoint is [0,0]).
  • The answer must be returned modulo 10^9 + 7.

Examples

Example 1

Input: count_checkpoint_paths([[2, 2]])

Output: 6

Example 2

Input: count_checkpoint_paths([[1, 0], [3, 2]])

Output: 6

Example 3

Input: count_checkpoint_paths([[1, 1], [3, 3], [5, 4]])

Output: 36

Hints

Hint 1

The number of monotone paths between two grid points depends only on the horizontal and vertical distances — look up or derive the formula involving a binomial coefficient.

Hint 2

Because checkpoints must be visited in the given order, the segments between consecutive checkpoints are independent, so multiply the per-segment path counts together.

Hint 3

Use Pascal's triangle or modular inverse-based factorials to compute large binomial coefficients under a prime modulus efficiently.