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.

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.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(m * n)

We visit each cell once and perform constant work for each direction

n
2n
โœ“ Linear Growth
Space Complexity
O(m * n)

We need a 3D DP array of size m ร— n ร— 4 to store lengths for each direction

n
2n
โšก Linearithmic Space

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 โ‰ค m, n โ‰ค 104
  • 1 โ‰ค m * n โ‰ค 104
  • mat[i][j] is either 0 or 1
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