Coding Software Engineer
Work with a one-dimensional array.
For Part 1:
0 represents a vacant position.1 represents a cake.For Part 2:
0 represents an unoccupied position.1 represents a person.2 represents a cake.The interview is divided into two tasks:
You receive:
A: a binary array where 1 denotes a cake and 0 denotes anything else.start: the index occupied by the person.Return the minimum distance from start to a cake. Return -1 when the array contains no cakes.
A = [0, 0, 0, 1, 0, 0, 1]
start = 1
Output:
2
Explanation: the nearest cake appears at position 3, which is two positions away.
A = [0,0, 0, 1, 0, 0, 1] start = 1
2
A person is located at index 1. The array contains vacant positions (0) and cakes (1).
The array now includes both people and cakes:
1 identifies a person.2 identifies a cake.0 identifies an empty slot.Give every person exactly one distinct cake, while allowing each cake to serve no more than one person, subject to these requirements:
Consequently, a question about one person can still require determining the complete optimal matching first.
line = [1, 0, 2, 0, 1, 0, 0, 0, 2]
# people at [0, 4], cakes at [2, 8]
Considering each person separately:
0 would choose cake 2 (distance 2).4 would also choose cake 2 (distance 2).The optimal one-to-one result is instead:
person 0 -> cake 2 (distance 2)person 4 -> cake 8 (distance 4)The total distance is 6.
Therefore, a query for person index 4 must return cake index 8, rather than that person's individually closest cake, index 2.
A = [0,0, 0, 1, 0, 0, 1] start = 1
2
A person is located at index 1. The array contains vacant positions (0) and cakes (1).