← Questions

Count warehouse robots boxed in on all four sides

0
AmazonCoding

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, larger y),
  • below it (same x, smaller y),
  • to its left (same y, smaller x), and
  • to its right (same y, larger x).

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, where n = 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 x and y always the same length, and is an empty input answered with 0?
  • 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 maximum y; for each row y, the minimum and maximum x.
  • A robot is idle when its y lies strictly between its column's min and max, and its x strictly between its row's min and max.
  • Two passes over the robots with hash maps: O(n) time and space, against the O(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

hashing · arrays · grid

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding