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

People and Cakes I

A hallway is a list of cells: 0 is empty, 1 holds a person and 2 holds a cake. Return the smallest distance between any person and any cake, measured in cells, or -1 if the hallway lacks one or the other.

minPersonCakeGap([1, 0, 0, 2])              ->  3
minPersonCakeGap([2, 0, 1, 0, 0, 2])        ->  2
minPersonCakeGap([1, 0, 0, 0])              ->  -1

One pass, constant extra space.

Hints

Hint 1

Walk the line once remembering the index of the last person and the last cake. Whenever you see one kind, the closest partner of the other kind behind you is the last one seen.

Hint 2

Checking only backwards is enough: every person–cake pair is seen when the later of the two is reached.

Asked at