Merge Event Windows Within Each Locality
Greedy & IntervalsAuto-graded · 16 test casesLast updated
Join two record lists by id, group event time ranges by locality, merge overlapping or touching ranges, and return the merged windows in a specified sort order.
You are given two lists of dictionaries describing gatherings and where they took place.
Events (first argument). Each dictionary has:
party_id: a string or an integer identifying the eventstart_timestamp: when the event beginsend_timestamp: when the event ends; it is always strictly later thanstart_timestamp
Places (second argument). Each dictionary has:
party_id: matches an event's idneighborhood: a stringcity: a stringstate: a string
Every party_id appears exactly once in the events list and exactly once in the places list.
A locality is the full triple (neighborhood, city, state). Two locations that share a neighborhood name but differ in city or state are different localities.
For a given locality, an active window is a maximal continuous stretch of time during which at least one event in that locality is in progress. Two events in the same locality belong to the same window if their time ranges overlap, or if one ends at exactly the moment the other starts.
Task
Write a function that combines the two lists and returns every active window for every locality.
Output
Return a list of dictionaries, one per active window, each with these keys:
neighborhoodcitystateblock_start_timestamp: the earliest start in the windowblock_end_timestamp: the latest end in the window
Sort the returned list by state, then city, then neighborhood, then block_start_timestamp, all in ascending order. If there are no events, return an empty list.
Timestamps are mutually comparable values of one consistent type within an input (for example integers, or ISO-formatted strings that sort chronologically). Return them exactly as given, without converting them.
Constraints
- Up to 100,000 events in total.
- The events list may be in any order.
end_timestamp > start_timestampfor every event.- Each
party_idhas exactly one matching entry in each list. - Your solution should run in about O(n log n) time.
Examples
Example 1
Input: merge_locality_windows([{'party_id': 'p1', 'start_timestamp': 1, 'end_timestamp': 4}, {'party_id': 'p2', 'start_timestamp': 4, 'end_timestamp': 7}, {'party_id': 'p3', 'start_timestamp': 9, 'end_timestamp': 12}], [{'party_id': 'p1', 'neighborhood': 'North', 'city': 'Metro', 'state': 'CA'}, {'party_id': 'p2', 'neighborhood': 'North', 'city': 'Metro', 'state': 'CA'}, {'party_id': 'p3', 'neighborhood': 'North', 'city': 'Metro', 'state': 'CA'}])
Output: [{'neighborhood': 'North', 'city': 'Metro', 'state': 'CA', 'block_start_timestamp': 1, 'block_end_timestamp': 7}, {'neighborhood': 'North', 'city': 'Metro', 'state': 'CA', 'block_start_timestamp': 9, 'block_end_timestamp': 12}]
Example 2
Input: merge_locality_windows([{'party_id': 1, 'start_timestamp': '2024-01-01T20:00:00', 'end_timestamp': '2024-01-01T22:00:00'}, {'party_id': 2, 'start_timestamp': '2024-01-01T19:00:00', 'end_timestamp': '2024-01-01T21:00:00'}], [{'party_id': 1, 'neighborhood': 'Central', 'city': 'Oakland', 'state': 'CA'}, {'party_id': 2, 'neighborhood': 'Central', 'city': 'Oakland', 'state': 'CA'}])
Output: [{'neighborhood': 'Central', 'city': 'Oakland', 'state': 'CA', 'block_start_timestamp': '2024-01-01T19:00:00', 'block_end_timestamp': '2024-01-01T22:00:00'}]
Hints
Hint 1
Start by building a dictionary from party_id to the (neighborhood, city, state) triple so that each event can be matched to its locality in constant time.
Hint 2
Group the (start, end) pairs by locality, then handle each group on its own. Sort a group by start time so a single left-to-right pass is enough to merge it.
Hint 3
While sweeping, extend the current window when the next start is less than or equal to the current window's end, and keep the larger of the two ends. Finally, sort all resulting records by (state, city, neighborhood, window start).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is the classic merge-intervals pattern, wrapped in a join step and a final ordering step.
- Join. Build a dictionary mapping each
party_idto its(neighborhood, city, state)triple from the places list. Looking up an event's locality is then O(1). - Group. Go through the events and append each
(start, end)pair to a list keyed by its locality triple. Using the whole triple matters: the same neighborhood name in two different cities is two different localities. - Merge per locality. Sort a group's ranges by start. Keep a current window
[cur_start, cur_end]and scan the rest:- If the next range's start is
<= cur_end, it overlaps or touches the window, so extend it withcur_end = max(cur_end, end). - Otherwise there is a real gap. Emit the current window and begin a new one from this range.
- After the scan, emit the last window.
- If the next range's start is
- Order. Sort all emitted records by
(state, city, neighborhood, block_start_timestamp).
Why it is correct
After sorting by start, when the scan reaches a range, the current window is exactly the union of all earlier ranges since the last emitted window, and that union is one continuous stretch.
- If the new start is
<= cur_end, the range touches or overlaps the window, so the union stays continuous and its right edge becomes the larger of the two ends. Taking the max keeps a nested range (such as[1, 10]followed by[2, 3]) from shrinking the window. - If the new start is
> cur_end, a gap exists. Every later range starts at or after this one, so none can reach back into the gap, which means the current window is maximal and can be emitted.
Using <= rather than < is what makes ranges like [1, 4] and [4, 7] merge into [1, 7], as the problem requires. Windows never cross localities, so merging each group independently is enough.
Complexity
With n events:
- Time: O(n log n). Building the map and grouping are O(n), sorting groups costs at most O(n log n) in total, each sweep is linear, and the final sort handles at most
nrecords. - Space: O(n) for the map, the groups and the output.
Reference solution
from typing import Dict, List
def merge_locality_windows(events: List[Dict], places: List[Dict]) -> List[Dict]:
place_by_id = {
p["party_id"]: (p["neighborhood"], p["city"], p["state"])
for p in places
}
grouped = {}
for ev in events:
key = place_by_id[ev["party_id"]]
grouped.setdefault(key, []).append((ev["start_timestamp"], ev["end_timestamp"]))
result = []
for (neighborhood, city, state), ranges in grouped.items():
ranges.sort(key=lambda r: r[0])
cur_start, cur_end = ranges[0]
for start, end in ranges[1:]:
if start <= cur_end:
if end > cur_end:
cur_end = end
else:
result.append({
"neighborhood": neighborhood,
"city": city,
"state": state,
"block_start_timestamp": cur_start,
"block_end_timestamp": cur_end,
})
cur_start, cur_end = start, end
result.append({
"neighborhood": neighborhood,
"city": city,
"state": state,
"block_start_timestamp": cur_start,
"block_end_timestamp": cur_end,
})
result.sort(key=lambda r: (r["state"], r["city"], r["neighborhood"],
r["block_start_timestamp"]))
return result