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

House Segments After Demolitions

Houses stand at distinct integer positions on a number line. Houses at consecutive positions belong to the same segment. The houses listed in queries are demolished one at a time, in order.

Return an array with the number of segments that remain after each demolition.

houses  = [1, 2, 3, 6, 7, 9]
queries = [6, 3, 7, 2, 9, 1]
result  = [3, 3, 2, 2, 1, 0]

Initially there are three segments: 1-3, 6-7 and 9. Removing 6 trims a segment (still 3), removing 3 trims another (3), removing 7 deletes a lone house (2), and so on.

Up to 200,000 houses at positions between -10^9 and 10^9. Every query is a distinct position that holds a house.

Hints

Hint 1

Removing a house only affects its relationship with the positions one below and one above it.

Hint 2

Three cases: both neighbours present (a segment splits), neither present (a segment disappears), exactly one present (a segment gets shorter).

Hint 3

Count the initial segments as the houses whose left neighbour is absent.

Topics

Asked at

Similar Problems6