Find robots by distances to the nearest blocker

0
Sign in

You are given an m x n board. Each cell is one of:

  • 'O': a robot
  • 'E': an empty cell
  • 'X': a blocker

You are also given a query of four integers [left, top, bottom, right]. For a robot, each number is the distance to the nearest blocker in that direction. Distance is the number of steps from the robot until you land on the blocker, so a blocker in the adjacent cell is distance 1. The edge of the board also acts as a blocker: if there is no 'X' in a direction, count the steps until you step off the board. Robots and empty cells do not block.

Return the positions [row, col] of every robot whose four distances match the query exactly, in row-major order. Return an empty list if no robot matches.

Then extend your solution: the board stays fixed and you receive many queries. Make each query as fast as you can.

Constraints

  • 1 <= m, n <= 1000
  • Up to 10^5 queries

Example 1

board = [["O","E","X"],
         ["E","O","E"],
         ["X","E","O"]]
query = [2, 2, 2, 2]

Output: [[1, 1]]. The center robot sees no 'X' in any direction; the board edge is two steps away each way.

Example 2

Same board, query = [1, 1, 2, 2]. Output: [[0, 0]]. The top-left robot touches the edge on its left and top, and an 'X' is two steps below it and two steps to its right.

UberTechnical phone screenMediumLast asked Aug 2026

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.