Assign Each Person the Nearest Cake in a One-Dimensional Row
SnowflakeSoftware Engineer · Technical ScreenLast updated
Given a one-dimensional row marking empty spots, people and cakes, return for each person the index of the nearest cake, breaking ties toward the smaller index. It tests linear scanning techniques for nearest-neighbor queries on a line and careful handling of ties and boundaries.
People and cakes stand in a single row of positions, described by an integer array whose values are 0, 1 or 2. The original question asks for the closest distance between a person and a cake; the follow-up asks you to assign every person the cake closest to them. Implement the follow-up: for each person, return the position of their nearest cake. The original answer is then the smallest of those distances.
Function Signature
def nearest_cakes(row: list[int]) -> list[int]:
Rules
row[i] == 0means positioniis empty,row[i] == 1means a person stands there, androw[i] == 2means a cake is there. Each position holds at most one thing.- The distance between positions
iandjisabs(i - j). Empty positions and other people do not block anyone. - Several people can be assigned the same cake; cakes are not used up.
- If two cakes are equally close to a person, assign the one with the smaller index.
- Return one cake index per person, ordered by the person's position from left to right.
Constraints
2 <= len(row) <= 10^5- Every
row[i]is0,1or2. rowcontains at least one1and at least one2.
Examples
Example 1
Input: row = [2, 1, 0, 1, 0, 0, 2, 1]
Output: [0, 0, 6]
The people stand at positions 1, 3 and 7, and the cakes are at 0 and 6. The person at 3 is 3 away from both cakes, so the tie goes to index 0. The closest person-cake distance in this row is 1.
Example 2
Input: row = [1, 1, 0, 2]
Output: [3, 3]
Both people share the only cake.
Example 3
Input: row = [0, 2, 1, 2, 0]
Output: [1]
The cakes at 1 and 3 are both 1 away, and the smaller index wins.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.