Longest Line of Consecutive One in Matrix - Problem

You're given an m x n binary matrix containing only 0s and 1s. Your task is to find the longest consecutive line of 1s in the matrix.

The line can extend in four different directions:

  • Horizontal (left to right)
  • Vertical (top to bottom)
  • Diagonal (top-left to bottom-right)
  • Anti-diagonal (top-right to bottom-left)

Return the length of the longest line of consecutive 1s found in any of these directions.

Example: In a matrix with a horizontal line of three 1s and a diagonal line of four 1s, you would return 4.

Input & Output

example_1.py — Basic Matrix
$ Input: mat = [[0,1,1,0],[0,1,1,0],[0,0,0,1]]
Output: 3
💡 Note: The longest line is the vertical line of three 1s in the second column, or the diagonal line in the bottom-right area.
example_2.py — Single Element
$ Input: mat = [[1,1,1,1]]
Output: 4
💡 Note: The entire row forms a horizontal line of four consecutive 1s.
example_3.py — Diagonal Pattern
$ Input: mat = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3
💡 Note: The main diagonal from top-left to bottom-right contains three consecutive 1s.

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 ≤ m, n ≤ 104
  • 1 ≤ m * n ≤ 104
  • mat[i][j] is either 0 or 1

Visualization

Tap to expand
Connect Four: Finding Longest StreakHorizontal Streak: 4Vertical: 3Diagonal: 3Winner: Horizontal streak with 4 consecutive pieces!
Understanding the Visualization
1
Set Up Scorekeeping
Create a tracking system for each position and direction
2
Process Each Position
For each disc, calculate streak length using previous positions
3
Track Maximum
Keep record of the longest streak found so far
4
Return Winner
Report the length of the longest consecutive line
Key Takeaway
🎯 Key Insight: Dynamic programming eliminates redundant calculations by building solutions incrementally, tracking the longest line ending at each position rather than starting from each position.
Asked in
Google 25 Facebook 18 Amazon 15 Microsoft 12
28.4K Views
Medium Frequency
~25 min Avg. Time
847 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