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
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
โ Linear Growth
Space Complexity
O(m * n)
We need a 3D DP array of size m ร n ร 4 to store lengths for each direction
โก 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code