Skip to main content

Longest Line of Consecutive One in Matrix - Solution & Explanation

MediumPremiumFree on FleetCodeArrayDynamic ProgrammingMatrix8 min readAsked at: Google
Practice this problem

Problem Statement

Given an m x n binary matrix mat, return the length of the longest line of consecutive one in the matrix.

The line could be horizontal, vertical, diagonal, or anti-diagonal.

 

Example 1:

Input: mat = [[0,1,1,0],[0,1,1,0],[0,0,0,1]]
Output: 3

Example 2:

Input: mat = [[1,1,1,1],[0,1,1,0],[0,0,0,1]]
Output: 4

 

Constraints:

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

Approach Overview

Problem Overview: Given a binary matrix, find the maximum number of consecutive 1s that appear in a straight line. A valid line can be horizontal, vertical, diagonal, or anti-diagonal. The goal is to scan the grid and return the length of the longest such sequence.

Approach 1: Brute Force Directional Scan (O(m*n*max(m,n)) time, O(1) space)

The straightforward method checks every cell containing 1 and extends in four directions: right, down, diagonal, and anti-diagonal. For each direction, keep moving while the next cell remains 1. Track the length and update the global maximum. This approach is simple but inefficient because the same sequences are recomputed multiple times. In dense matrices, repeated directional scans significantly increase runtime.

Approach 2: Dynamic Programming with Direction States (O(m*n) time, O(m*n) space)

The efficient solution uses dynamic programming to track streak lengths ending at each cell. For every matrix[i][j] == 1, maintain four DP values: horizontal, vertical, diagonal, and anti-diagonal. Each value extends from a previously computed neighbor. Horizontal depends on (i, j-1), vertical on (i-1, j), diagonal on (i-1, j-1), and anti-diagonal on (i-1, j+1). Add 1 to the corresponding previous value and store it. This avoids re-scanning sequences and ensures each cell is processed once.

Implementation typically uses a 3D DP array dp[i][j][4] or four separate matrices. When the cell value is 0, all streak counts remain zero. When it's 1, compute the four directions using previously calculated states. Track the maximum value seen across all directions. The algorithm runs in O(m*n) time because each cell performs constant work.

An alternative optimization compresses memory by keeping only the previous row for vertical and diagonal transitions while computing the current row for horizontal and anti-diagonal values. This reduces space to O(n) while maintaining the same time complexity.

This problem is a classic application of array traversal combined with directional dynamic programming. The key insight is recognizing overlapping subproblems: the longest line ending at a cell depends on previously solved neighbors rather than scanning entire lines repeatedly.

Recommended for interviews: The dynamic programming approach is what interviewers expect. Brute force shows you understand the four valid directions, but the DP solution demonstrates optimization skills and the ability to reuse computed state. Explaining how each direction depends on a specific neighbor is usually the critical insight interviewers look for.

Solution

We define f[i][j][k] to represent the length of the longest consecutive 1s ending at (i, j) in direction k. The value range of k is 0, 1, 2, 3, representing horizontal, vertical, diagonal, and anti-diagonal directions, respectively.

We can also use four 2D arrays to represent the length of the longest consecutive 1s in the four directions.

We traverse the matrix, and when we encounter 1, we update the value of f[i][j][k]. For each position (i, j), we only need to update the values in its four directions. Then we update the answer.

The time complexity is O(m times n), and the space complexity is O(m times n), where m and n are the number of rows and columns in the matrix, respectively.

Code

Python

Java

C++

Go

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Directional ScanO(m*n*max(m,n))O(1)Good for understanding the problem and verifying all four directions before optimizing
Dynamic Programming with 4 Direction StatesO(m*n)O(m*n)Standard optimal solution for interviews and large matrices
Space Optimized DPO(m*n)O(n)Useful when memory usage matters while keeping the same optimal runtime

Video Solution

LeetCode 562. Longest Line of Consecutive One in Matrix • Happy Coding • 2,574 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Longest Line of Consecutive One in Matrix easy or hard?
The problem is rated Medium on LeetCode. The challenge is recognizing that four directional sequences must be tracked simultaneously and that dynamic programming avoids repeated scanning of the same lines.
Longest Line of Consecutive One in Matrix Python/Java solution
The typical implementation uses a DP table where dp[i][j][k] represents the longest streak ending at cell (i, j) for one of four directions. Python, Java, C++, and Go implementations follow the same logic: update directional states based on neighboring cells and track the maximum length.
How to solve Longest Line of Consecutive One in Matrix in O(n)?
Process the matrix using dynamic programming. For every cell with value 1, compute four directional streaks using previously computed neighbors: left, up, up-left, and up-right. This ensures the entire grid is processed in O(m*n) time without repeatedly scanning lines.
What is the best approach for Longest Line of Consecutive One in Matrix?
Dynamic programming is the best approach. For each cell containing 1, maintain four counts representing horizontal, vertical, diagonal, and anti-diagonal lines ending at that cell. Each state extends from a neighboring cell's value, allowing the matrix to be processed in O(m*n) time.
Is Longest Line of Consecutive One in Matrix asked at Google/Amazon/Meta?
Matrix dynamic programming problems like this commonly appear in interviews at companies such as Amazon, Google, and Meta. Variants involving directional DP or longest sequences in grids are frequently used to test grid traversal and DP reasoning.
What data structure is used in Longest Line of Consecutive One in Matrix?
The solution primarily uses arrays and dynamic programming tables. A 3D DP array or four separate matrices track consecutive counts for horizontal, vertical, diagonal, and anti-diagonal directions.
What is the time complexity of Longest Line of Consecutive One in Matrix?
The optimal dynamic programming solution runs in O(m*n) time, where m is the number of rows and n is the number of columns. Each cell is processed once while updating four directional counts, resulting in constant work per cell.

Ready to solve this problem?

Practice Longest Line of Consecutive One in Matrix with our built-in code editor and test cases.

Practice on FleetCode