call(back)
Algorithms & Data StructureseasySign in to star problems

People and Cakes III

The same hallway: a list of cells where 0 is empty, 1 holds a person and 2 holds a cake. For every person, in hallway order, return the distance to the nearest cake, measured in cells. If the hallway has no cake, every person gets -1.

cakeDistances([1, 0, 2, 0, 1, 2])  ->  [2, 1]
cakeDistances([2, 1, 0, 0, 2, 1])  ->  [1, 1]
cakeDistances([1, 0, 1])           ->  [-1, -1]

Hints

Hint 1

Each person's answer is the smaller of two things: the distance to the last cake seen going right, and to the last cake seen going left.

Hint 2

Two passes, each carrying the index of the most recent cake, cover both directions in O(n).

Topics

Asked at

Similar Problems6