FastPrepLongest Border-Ending Diagonal Pattern

Longest Border-Ending Diagonal Pattern

ZipRecruiter logoZipRecruiter● MediumNEW GRADOA
Learn

Problem statement

For this exercise, use the callable contract below.

Given a rectangular integer matrix matrix, find the longest diagonal segment that matches the infinite pattern 1, 2, 0, 2, 0, ....

A valid segment:

  • starts at any matrix cell whose value is 1;
  • continues in exactly one of the four diagonal directions;
  • matches 2 after the initial 1, then alternates 0 and 2; and
  • ends at a cell on the first row, last row, first column, or last column.

Return the maximum length of a valid segment.

Function

longestBorderDiagonal(matrix: int[][]) → int

Examples

Example 1

matrix = [[0,0,1,2],[0,2,2,2],[2,1,0,1]]return = 3

Starting at matrix[2][3] and moving up-left produces 1, 2, 0 at cells (2,3), (1,2), and (0,1). The last cell is on the first row, so this is a valid length-3 segment. No longer valid segment exists.

Constraints

  • matrix is non-empty and rectangular.
  • Every matrix value is 0, 1, or 2.
  • A segment moves by one row and one column at each step and never changes direction.
  • A solution with time complexity no worse than O(matrix.length^2 * matrix[0].length^2) fits the source's execution limit.

More ZipRecruiter problems

See ZipRecruiter hiring insights
public int longestBorderDiagonal(int[][] matrix) {
    // write your code here
}
matrix[[0,0,1,2],[0,2,2,2],[2,1,0,1]]
expected3
Checking account…