Length of Longest V-Shaped Diagonal Segment - Problem

You are given a 2D integer matrix grid of size n x m, where each element is either 0, 1, or 2.

A V-shaped diagonal segment is defined as:

  • The segment starts with 1
  • The subsequent elements follow this infinite sequence: 2, 0, 2, 0, ...
  • The segment starts along a diagonal direction (top-left to bottom-right, bottom-right to top-left, top-right to bottom-left, or bottom-left to top-right)
  • Continues the sequence in the same diagonal direction
  • Makes at most one clockwise 90-degree turn to another diagonal direction while maintaining the sequence

Return the length of the longest V-shaped diagonal segment. If no valid segment exists, return 0.

Input & Output

Example 1 — Basic V-Shape
$ Input: grid = [[1,2,0],[0,2,0],[1,0,2]]
Output: 1
💡 Note: Starting at (0,0) with value 1, no valid continuation exists following the sequence 1→2→0→2→0... The grid at (1,1) has value 2 but position 2 in sequence expects 0.
Example 2 — No Valid Segment
$ Input: grid = [[1,1,1],[1,1,1],[1,1,1]]
Output: 1
💡 Note: Only single cells with value 1 can form segments of length 1, as the sequence 2,0,2,0... cannot be followed.
Example 3 — V-Shape with Turn
$ Input: grid = [[1,0,0],[2,0,0],[0,2,0]]
Output: 1
💡 Note: Start at (0,0) with value 1. Going down to (1,0) gives value 2, but this is not a diagonal direction. Following diagonal directions, no valid sequence of length > 1 exists.

Constraints

  • 1 ≤ n, m ≤ 1000
  • grid[i][j] ∈ {0, 1, 2}
  • At least one element in the grid

Visualization

Tap to expand
V-Shaped Diagonal Segment INPUT 3x3 Grid Matrix 1 2 0 0 2 0 1 0 2 Pattern: 1 --> 2 --> 0 --> 2 --> 0... Start (1) Value 2 Value 0 Input Array: grid = [[1,2,0], [0,2,0],[1,0,2]] ALGORITHM (DFS) 1 Find Starting Points Locate all cells with value 1 2 DFS in 4 Diagonals Explore: NE, SE, SW, NW 3 Follow Pattern Match: 2,0,2,0... sequence 4 Handle Turn Max 1 clockwise 90 deg turn V-Shape Example: 1 2 0 2 turn FINAL RESULT 1 2 0 0 2 0 1 0 2 Longest V-Path Found: (0,0) --> (1,1) --> (2,2) + turn --> (1,1) = 4 cells OUTPUT 4 OK Key Insight: DFS explores all diagonal paths starting from cells with value 1. The V-shape pattern allows at most ONE clockwise 90-degree turn. Track: current direction, turn status, and expected next value (alternating 2,0,2,0...). Maximum path length across all starting points = answer. TutorialsPoint - Length of Longest V-Shaped Diagonal Segment | DFS Approach
Asked in
Google 15 Microsoft 12 Amazon 8
8.5K Views
Medium Frequency
~35 min Avg. Time
240 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