Count warehouse robots boxed in on all four sides
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Amazon. It tests hashing, arrays and grid.
A warehouse floor is modeled as an integer grid. Each delivery robot sits at a point (x[i], y[i]), and no two robots share a point.
A robot is idle when there is at least one other robot:
- above it (same
x, largery), - below it (same
x, smallery), - to its left (same
y, smallerx), and - to its right (same
y, largerx).
The other robots can be any distance away; they only need to share the row or column.
Implement:
def count_idle_drives(x: list[int], y: list[int]) -> int: ...
Return the number of idle robots.
Constraints
-
0 <= n <= 10^5, wheren = len(x) == len(y) -10^9 <= x[i], y[i] <= 10^9- All points are distinct.
Example 1
x = [0, 0, 0, 1, 1, 1, 2, 2, 2]
y = [0, 1, 2, 0, 1, 2, 0, 1, 2]
-> 1
The robots fill a 3x3 square. Only the centre (1, 1) has robots on all four sides.
Example 2
x = [5, 5, 5, 2, 9]
y = [0, 4, 8, 4, 4]
-> 1
The robot at (5, 4) has (5, 8) above, (5, 0) below, (2, 4) to the left and (9, 4) to the right. None of them is adjacent, but they still count. Every other robot is missing at least one side.
Clarifying questions
- Do the robots on each side need to be adjacent, or anywhere along the row or column? (Anywhere, per the statement.)
- Are
xandyalways the same length, and is an empty input answered with0? - Is the answer only a count, or also the list of idle robots?
- Will the grid change, or is this a one-time count?
What a strong answer covers
- For each column
x, records the minimum and maximumy; for each rowy, the minimum and maximumx. - A robot is idle when its
ylies strictly between its column's min and max, and itsxstrictly between its row's min and max. - Two passes over the robots with hash maps:
O(n)time and space, against theO(n^2)pairwise check. - Tests the 3x3 square, a single row of robots (none idle), a lone robot, and large negative coordinates.
Follow-ups
- Robots are added and removed: keep the count current after each update.
- Require the neighbours to be within distance
k. - Count robots boxed in on at least three sides.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
