Skip to main content

Count Good Integers on a Grid Path - Solution & Explanation

HardDynamic Programming18 min read
Practice this problem

Problem Statement

You are given two integers l and r, and a string directions consisting of exactly three 'D' characters and three 'R' characters.

For each integer x in the range [l, r] (inclusive), perform the following steps:

  1. If x has fewer than 16 digits, pad it on the left with leading zeros to obtain a 16-digit string.
  2. Place the 16 digits into a 4 × 4 grid in row-major order (the first 4 digits form the first row from left to right, the next 4 digits form the second row, and so on).
  3. Starting at the top-left cell (row = 0, column = 0), apply the 6 characters of directions in order:
    • 'D' increments the row by 1.
    • 'R' increments the column by 1.
  4. Record the sequence of digits visited along the path (including the starting cell), producing a sequence of length 7.

The integer x is considered good if the recorded sequence is non-decreasing.

Return an integer representing the number of good integers in the range [l, r].

 

Example 1:

Input: l = 8, r = 10, directions = "DDDRRR"

Output: 2

Explanation:

The grid for x = 8:

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 8
  • Path: (0,0) → (1,0) → (2,0) → (3,0) → (3,1) → (3,2) → (3,3)
  • The sequence of digits visited is [0, 0, 0, 0, 0, 0, 8].
  • As the sequence of digits visited is non-decreasing, 8 is a good integer.

The grid for x = 9:

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 9
  • The sequence of digits visited is [0, 0, 0, 0, 0, 0, 9].
  • As the sequence of digits visited is non-decreasing, 9 is a good integer.

The grid for x = 10:

0 0 0 0
0 0 0 0
0 0 0 0
0 0 1 0
  • The sequence of digits visited is [0, 0, 0, 0, 0, 1, 0].
  • As the sequence of digits visited is not non-decreasing, 10 is not a good integer.
  • Hence, only 8 and 9 are good, giving a total of 2 good integers in the range.

Example 2:

Input: l = 123456789, r = 123456790, directions = "DDRRDR"

Output: 1

Explanation:

The grid for x = 123456789:

0 0 0 0
0 0 0 1
2 3 4 5
6 7 8 9
  • Path: (0,0) → (1,0) → (2,0) → (2,1) → (2,2) → (3,2) → (3,3)
  • The sequence of digits visited is [0, 0, 2, 3, 4, 8, 9].
  • As the sequence of digits visited is non-decreasing, 123456789 is a good integer.

The grid for x = 123456790:

0 0 0 0
0 0 0 1
2 3 4 5
6 7 9 0
  • The sequence of digits visited is [0, 0, 2, 3, 4, 9, 0].
  • As the sequence of digits visited is not non-decreasing, 123456790 is not a good integer.
  • Hence, only 123456789 is good, giving a total of 1 good integer in the range.

Example 3:

Input: l = 1288561398769758, r = 1288561398769758, directions = "RRRDDD"

Output: 0

Explanation:

The grid for x = 1288561398769758:

1 2 8 8
5 6 1 3
9 8 7 6
9 7 5 8
  • Path: (0,0) → (0,1) → (0,2) → (0,3) → (1,3) → (2,3) → (3,3)
  • The sequence of digits visited is [1, 2, 8, 8, 3, 6, 8].
  • ​​​​​​​As the sequence of digits visited is not non-decreasing, 1288561398769758 is not a good integer.
  • No numbers are good, giving a total of 0 good integers in the range.

 

Constraints:

  • 1 <= l <= r <= 9 × 1015
  • directions.length == 6
  • directions consists of exactly three 'D' characters and three 'R' characters.

Approach Overview

Problem Overview: You move from the top-left to the bottom-right of a grid while forming an integer from the digits along the path. The goal is to count how many paths produce a good integer (usually defined by a divisibility or remainder constraint). Since each step extends the number with a new digit, the solution must efficiently track partial results while exploring grid paths.

Approach 1: Brute Force DFS Enumeration (Exponential Time, O(2^(m+n)) time, O(m+n) space)

The most direct idea is to enumerate every possible path from the top-left to the bottom-right using depth‑first search. While traversing, append the current grid digit to the growing number. When you reach the destination, check if the constructed integer satisfies the "good" condition. This approach is easy to implement but quickly becomes impractical because the number of paths in a grid grows combinatorially.

Approach 2: DFS with Memoization on Remainders (O(m*n*k) time, O(m*n*k) space)

Instead of storing the full integer, track its remainder with respect to the constraint (for example mod k). Each state becomes (row, col, remainder). When you move to the next cell, update the remainder using (remainder * 10 + digit) % k. Memoization avoids recomputing results for the same state. This dramatically reduces the search space because there are only m * n * k possible states.

Approach 3: Bottom-Up Dynamic Programming (O(m*n*k) time, O(m*n*k) space)

A tabulation approach builds results iteratively. Maintain a DP table where dp[i][j][r] represents the number of ways to reach cell (i,j) with remainder r. Transition from the top or left neighbor by updating the remainder after appending the current digit. This avoids recursion overhead and often runs faster in practice. The technique closely follows standard grid traversal patterns seen in dynamic programming and grid problems.

Approach 4: Space Optimized DP (O(m*n*k) time, O(n*k) space)

Because each row only depends on the previous row and the current row’s left neighbor, the 3D DP table can be compressed. Keep rolling arrays for the current and previous rows while still tracking remainder states. This reduces memory usage significantly while preserving the same transition logic used in the standard DP approach. The idea is similar to optimization techniques commonly used in dynamic programming and path counting problems.

Recommended for interviews: Start by describing the brute-force DFS to demonstrate understanding of path enumeration. Then transition to the remainder-based DP state (i, j, remainder). Interviewers typically expect the optimized dynamic programming solution because it reduces exponential exploration to O(m*n*k) by reusing subproblem results.

Solution

Since the 6 characters in directions determine the path, we can preprocess a boolean array key of length 16, where key[i] indicates whether the i-th cell visited along the path is a key cell (i.e., a cell visited on the path). We can compute the key array based on directions.

Next, we use digit dynamic programming (digit DP) to count the number of integers in the range [l, r] that satisfy the condition. We convert r and l - 1 to 16-digit strings s, then use a recursive function to count the number of valid integers in [0, r], and subtract the count in [0, l - 1] to get the answer for [l, r].

We define a recursive function dfs(pos, last, lim), where pos is the current digit position, last is the digit of the previous key cell, and lim indicates whether the current digit is restricted by s (i.e., whether the current prefix matches s so far).

In the recursive function, we first check if all positions have been processed; if so, return 1. Otherwise, we determine the range of digits to try at the current position: if key[pos] is true, the digit must be at least last; otherwise, it can start from 0. The upper bound is s[pos] if lim is true, or 9 otherwise.

We enumerate all possible digits for the current position, updating last to the current digit if this is a key cell, or keeping it unchanged otherwise. We also update lim: if the current digit equals the upper bound, lim remains true; otherwise, it becomes false. We sum the results of all branches and return the total.

The time complexity is O(D^2 times log r) and the space complexity is O(D times log r), where D = 10 is the range of digits and log r is the number of digits in r.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force DFSO(2^(m+n))O(m+n)Small grids or for explaining the basic path enumeration idea
DFS with MemoizationO(m*n*k)O(m*n*k)Top-down solution when recursion with caching is easier to reason about
Bottom-Up Dynamic ProgrammingO(m*n*k)O(m*n*k)Most common interview solution with clear state transitions
Space Optimized DPO(m*n*k)O(n*k)Large grids where memory optimization matters

Video Solution

Leetcode 3906 | Count Good Integers on a Grid Path | Leetcode weekly contest 498 • CodeWithMeGuys • 529 views views

Watch 5 more video solutions →

Frequently Asked Questions

Is Count Good Integers on a Grid Path easy or hard?
The problem is classified as Hard because it combines grid traversal with number construction and modular arithmetic. Efficiently managing states and avoiding exponential path exploration requires dynamic programming with careful remainder tracking.
Count Good Integers on a Grid Path Python/Java solution
Python, Java, and C++ implementations typically build a DP table where dp[i][j][r] stores the number of ways to reach cell (i,j) with remainder r. Each transition updates the remainder using (previousRemainder * 10 + digit) % k. The final answer is the count of paths reaching the bottom-right cell with remainder 0.
How to solve Count Good Integers on a Grid Path in O(n)?
A pure O(n) solution is not possible because every grid cell must be processed. The closest optimization uses O(m*n*k) time with space reduced to O(n*k) using rolling arrays. This keeps only the previous and current rows of DP states instead of the full 3D table.
What is the best approach for Count Good Integers on a Grid Path?
The most efficient approach uses dynamic programming with a state that tracks the grid position and the current remainder of the formed number. By storing states as (row, column, remainder), you avoid recomputing paths that produce the same remainder at the same cell. This reduces the complexity to O(m*n*k), where k is the divisor or constraint parameter.
Is Count Good Integers on a Grid Path asked at Google/Amazon/Meta?
Grid dynamic programming problems with remainder tracking appear frequently in interviews at companies like Google, Amazon, and Meta. Variants often involve counting paths with divisibility constraints, modulo conditions, or digit concatenation rules.
What data structure is used in Count Good Integers on a Grid Path?
The solution primarily uses a dynamic programming table indexed by grid coordinates and remainder state. In top-down implementations, a hash map or memoization cache stores computed states. In bottom-up solutions, a 3D array or rolling DP arrays are typically used.
What is the time complexity of Count Good Integers on a Grid Path?
The optimal dynamic programming solution runs in O(m*n*k) time because each cell processes all possible remainder states. For each state, transitions occur from the top or left neighbor. Space complexity is also O(m*n*k) unless a rolling array optimization is applied.

Ready to solve this problem?

Practice Count Good Integers on a Grid Path with our built-in code editor and test cases.

Practice on FleetCode