KatInterview

Closest Bakery Stall for Every Shopper on a Street

Arrays & HashingAuto-graded · 25 test cases
MediumAuto-gradedArrays & Hashingarraystwo-pointersprefix-suffix

Last updated

For each shopper on a line, find the closest stall index, with ties going to the lower index, testing two-sided linear scans for nearest-neighbor lookups.

Closest Stall for Every Shopper

A street is modeled as a row of numbered slots, given as an integer list street. Each slot contains one of three values:

  • 0: the slot is vacant.
  • 1: a shopper is standing in the slot.
  • 2: a stall selling cake is in the slot.

A slot holds at most one thing. The distance between slots i and j is abs(i - j). Vacant slots, other shoppers and other stalls never block anyone, so only the slot numbers matter.

For every shopper, determine which stall is closest to them and report that stall's slot index.

Rules

  • A stall can serve any number of shoppers, so several shoppers may be given the same stall.
  • If two stalls are at the same minimal distance from a shopper, choose the one with the smaller index.
  • Return a list with one entry per shopper, ordered by the shopper's slot from left to right. Each entry is the slot index of the chosen stall (not a distance).

Constraints

  • 2 <= len(street) <= 10^5
  • Each street[i] is 0, 1 or 2.
  • street contains at least one 1 and at least one 2.

Examples

Example 1

Input: closest_stalls([2, 1, 0, 1, 0, 0, 2, 1])

Output: [0, 0, 6]

Example 2

Input: closest_stalls([1, 1, 0, 2])

Output: [3, 3]

Example 3

Input: closest_stalls([0, 2, 1, 2, 0])

Output: [1]

Hints

Hint 1

For a given shopper, only two stalls can possibly be the best: the nearest one on the left and the nearest one on the right. Anything further out on either side is strictly worse.

Hint 2

Precompute, for every slot, the index of the closest stall at or before it using a left-to-right pass, and the closest stall at or after it using a right-to-left pass. Use a sentinel such as -1 for 'none yet'.

Hint 3

When comparing the two candidates, handle a missing side first, then pick the left stall when the distances are equal, since it always has the smaller index.