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: 2
💡 Note: The longest lines are horizontal lines of two 1s in rows 0 and 1, or vertical lines of two 1s in columns 1 and 2.
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
Longest Line of Consecutive One in Matrix INPUT Binary Matrix (3x4) 0 1 1 0 0 1 1 0 0 0 0 1 4 Directions to Check: Horizontal Vertical Diagonal Anti-diag mat = [[0,1,1,0], [0,1,1,0], [0,0,0,1]] ALGORITHM STEPS 1 Initialize DP Array Create dp[m][n][4] for 4 directions at each cell 2 Traverse Matrix For each cell (i,j), if mat[i][j] == 1 3 Update DP Values H: dp[i][j-1][0] + 1 V: dp[i-1][j][1] + 1 D: dp[i-1][j-1][2] + 1 A: dp[i-1][j+1][3] + 1 4 Track Maximum Update max with max of all 4 directions Time: O(m * n) Space: O(m * n) Optimal DP Solution FINAL RESULT Diagonal Line Found (length 3) 0 1 1 0 0 1 1 0 0 0 0 1 Output 3 [OK] Diagonal verified All Directions Max: H:2 V:2 D:3 A:1 Maximum = 3 (Diagonal) Key Insight: Use Dynamic Programming with a 3D array dp[i][j][k] where k represents 4 directions (horizontal, vertical, diagonal, anti-diagonal). For each cell with value 1, extend the count from its predecessor in each direction. This avoids recounting and achieves O(m*n) time complexity. Space can be optimized to O(n) using rolling arrays. TutorialsPoint - Longest Line of Consecutive One in Matrix | Optimal DP Solution
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