Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Distance to the nearest zero

Medium · Target 20 minutes · Graphs · Type asked atGoogleAmazon

A grid holds 0s and 1s, with at least one 0. For every cell, return the number of steps to the nearest cell holding 0, where a step moves up, down, left or right. Cells that hold 0 are at distance 0.

Examples

InputOutputWhy
mat = [[0,0,0],[0,1,0],[1,1,1]][[0,0,0],[0,1,0],[1,2,1]]The bottom-middle cell is two steps from the nearest 0.
mat = [[1,1,1],[1,1,1],[1,1,0]][[4,3,2],[3,2,1],[2,1,0]]A single 0 in the corner.
mat = [[0,1,1,1,1]][[0,1,2,3,4]]One row.

Constraints

  • 1 ≤ rows, cols, and rows · cols ≤ 10⁴
  • At least one cell is 0

Hints

Hint 1

A breadth-first search from each 1 is correct but costs O((rows · cols)²).

Hint 2

Turn it around: search outwards from the zeros. Put every 0 in the queue at distance 0 before starting.

Hint 3

The first time the search reaches a cell, it is from the nearest zero. Mark it then.

Where people lose marks

  • One search per cell: correct but quadratic, and too slow at 10⁴ cells.
  • Seeding the queue with one zero and treating the others as ordinary cells.
  • Updating a distance after the cell has already been reached.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.