Maximum Trailing Zeros in a Cornered Path - Problem

You are given a 2D integer array grid of size m x n, where each cell contains a positive integer.

A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell.

The product of a path is defined as the product of all the values in the path.

Return the maximum number of trailing zeros in the product of a cornered path found in grid.

Note:

  • Horizontal movement means moving in either the left or right direction.
  • Vertical movement means moving in either the up or down direction.

Input & Output

Example 1 — Basic 3×3 Grid
$ Input: grid = [[23,17,15],[3,5,14],[9,6,1]]
Output: 3
💡 Note: The path (1,0)→(1,1)→(1,2)→(2,2) gives product 3×5×14×1 = 210. Since 210 = 2¹×3×5¹×7, it has min(1,1) = 1 trailing zero. However, the path (2,0)→(2,1)→(1,1)→(0,1) gives 9×6×5×17 = 4590 = 2¹×3²×5¹×17, which has 1 trailing zero. The optimal path yields 3 trailing zeros.
Example 2 — Single Row
$ Input: grid = [[1,5,2]]
Output: 1
💡 Note: Path covers all cells: 1×5×2 = 10 = 2¹×5¹, giving min(1,1) = 1 trailing zero.
Example 3 — Powers of 10
$ Input: grid = [[10,100],[1000,1]]
Output: 5
💡 Note: Path (0,0)→(0,1)→(1,1) gives 10×100×1 = 1000 = 2³×5³, so min(3,3) = 3 trailing zeros. Path (1,0)→(0,0)→(0,1) gives 1000×10×100 = 10⁶, which has 6 trailing zeros, but optimal L-shaped path gives 5.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 105
  • 1 ≤ m × n ≤ 105
  • 1 ≤ grid[i][j] ≤ 1000

Visualization

Tap to expand
INPUT GRIDALGORITHMRESULT23171535149613×3 matrix with positive integersFind L-shaped path with max zeros1Count factors 2 & 52Build prefix sums3Try all L-shaped paths4Return max zeros foundZeros = min(factors of 2, factors of 5)Use prefix sums for O(1) range queries3trailing zerosMaximum found in optimalcornered path through gridKey Insight:Trailing zeros come from factors of 10 = 2×5. Count factors separately and use prefix sumsfor efficient range queries in any L-shaped path through the matrix.TutorialsPoint - Maximum Trailing Zeros in Cornered Path | Prefix Sum Optimization
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 6
23.4K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen