Find the Longest Straight Run of One Color
GoogleSoftware Engineer · Technical ScreenLast updated
Tests grid traversal and dynamic programming to find the maximum consecutive sequence of identical elements along horizontal, vertical, and diagonal lines.
Problem Statement
Given an m x n 2D grid of integers representing colors, find the length of the longest straight contiguous line segment of cells having the exact same color.
A line segment can run in any of the four straight directions:
- Horizontal (left to right)
- Vertical (top to bottom)
- Main diagonal (top-left to bottom-right,
+1row,+1col) - Anti-diagonal (top-right to bottom-left,
+1row,-1col)
Return the maximum number of cells in any such valid run. If the grid is empty, return 0.
Function Signature
def longest_straight_run(grid: list[list[int]]) -> int:
pass
Input & Output Format
- Input:
grid, a list of lists of integers, wheregrid[r][c]represents the color of the cell at rowrand columnc. - Output: An integer representing the length of the longest straight sequence of identical colors.
Constraints
0 <= m, n <= 10000 <= m * n <= 10^6-10^9 <= grid[r][c] <= 10^9
Examples
Example 1
Input: grid = [
[1, 2, 1, 3],
[2, 1, 3, 1],
[1, 3, 1, 1],
[3, 1, 2, 1]
]
Output: 4
Explanation: The main diagonal starting at (0, 0) and ending at (3, 3) has values [1, 1, 1, 1], giving a length of 4.
Example 2
Input: grid = [
[5, 5, 5, 2],
[1, 5, 2, 2],
[3, 5, 2, 2]
]
Output: 3
Explanation:
- The top row has three consecutive 5s: (0, 0), (0, 1), (0, 2).
- The second column has three consecutive 5s: (0, 1), (1, 1), (2, 1).
Both yield a maximum length of 3.
Edge Cases
- Empty grid (
m = 0orn = 0): should return0. - Grid with a single element (
1 x 1): should return1. - All elements are different: should return
1. - All elements are identical: should return
max(m, n, min(m, n)).
Hints
Hint 1
Notice that there are only four unique line orientations: horizontal, vertical, main diagonal, and anti-diagonal.
Hint 2
For any cell (r, c) and direction vector (dr, dc), the run length ending at (r, c) is 1 + run_length at (r - dr, c - dc) if their colors match, or 1 otherwise.
Hint 3
Instead of storing a full 3D DP table of size m x n x 4, can you process each direction independently or maintain only the necessary previous states to reduce memory?
Follow-up questions
- How would you modify your solution to return the starting and ending coordinates of the longest segment rather than just its length?
- If the grid rows are streamed line-by-line from a large file, what is the minimum auxiliary memory needed to find the answer?
- Suppose cell value 0 represents a wildcard that can match any color. How would you find the longest run of a single color?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.