KatInterview

Match Cells by Four-Way Gap to Nearest Blocker

Arrays & HashingAuto-graded · 21 test cases
MediumAuto-gradedArrays & Hashinggridmatrixprefix-sweep

Last updated

Compute, for every empty cell, the gap to the nearest blocker in each of four directions using linear sweeps, then return the cells whose four gaps equal a given target.

Four-Way Gap Matching

A warehouse floor is modeled as a rectangular grid. Each cell is either free (0) or blocked (1).

For a free cell, its profile is a list of four gaps, in this fixed order:

[up, down, left, right]

The gap in a direction is defined as follows:

  • Walk from the cell in that direction, one step at a time, until you reach a blocked cell.
  • The gap is the number of free cells strictly between the starting cell and that first blocked cell. A blocked cell directly next to the start gives a gap of 0.
  • If you leave the grid without meeting any blocked cell, the gap is -1. The grid boundary does not count as a blocker.

Given the grid and a target profile of four integers, return the coordinates of every free cell whose profile is exactly equal to the target.

Output format

  • Return a list of [row, column] pairs (each a list of two integers), using 0-based indices.
  • List the pairs in row-major order: increasing row, and within a row increasing column.
  • Blocked cells are never part of the answer.
  • If no cell matches, return an empty list.

Constraints

  • 1 <= M, N <= 500, where the grid has M rows and N columns.
  • grid[r][c] is either 0 (free) or 1 (blocked).
  • target contains exactly 4 integers, in the order [up, down, left, right]. A value of -1 means "no blocker in that direction".
  • A grid with no blocked cells, or one made up entirely of blocked cells, is possible.

Examples

Example 1

Input: find_cells_by_gap_profile([[0, 0, 1], [0, 0, 0], [1, 0, 0]], [2, 1, 1, 0])

Output: []

Hints

Hint 1

Checking each cell by walking outward in four directions is too slow for a 500 x 500 grid. Look for work that can be shared between neighboring cells.

Hint 2

Sweep each column top to bottom while remembering the row of the most recent blocked cell. The up gap of a free cell is then its row minus that row minus one, or -1 if none has been seen yet.

Hint 3

Do the same in the other three directions (bottom to top, left to right, right to left), then make one final pass comparing the four values of each free cell with the target.