Locate a Traveler's Airport by Timestamp
Data Structure DesignAuto-graded · 14 test casesLast updated
Process a batch of operations that load travel records and answer per-user point-in-time location queries using grouping, sorting and binary search.
Where Was the Traveler?
You are building a small lookup service for travel records. Each record is a trip written as [user_id, airport_code, start_time, end_time]. It means that the user was at airport_code for every moment in the closed interval [start_time, end_time], so both endpoints are included.
The service is driven by a batch of commands. You write a single function that receives two parallel lists, operations and arguments, processes the commands in order, and returns one result per command.
Commands
"__init__": the matching entry inargumentsis a list with one element, the list of trips. Discard any data loaded earlier and replace it with these trips. RecordNoneas the result."get_airport": the matching entry inargumentsis[user_id, timestamp]. Record the airport code where that user was at that timestamp, orNoneif the user was not at any airport at that moment (including when the user has no trips at all).- Any other operation name must raise a
ValueError.
If a "get_airport" command appears before any "__init__", there is no data, so the result is None.
Rules
- A user is at no more than one airport at any moment.
- Trips belonging to the same user never overlap in time.
- Trips may be given in any order, and the same user's trips may be spread throughout the list.
- A trip with
start_time == end_timeis valid and covers exactly that one moment. - Each trip may arrive as a list or a tuple.
Output
A list with one entry per command, in order: None for "__init__", and an airport code string or None for each "get_airport".
The number of trips can be large, so answering a query should be much faster than scanning every trip.
Constraints
len(operations) == len(arguments).user_idandairport_codeare strings;start_time,end_timeandtimestampare integers.start_time <= end_timefor every trip.- Trips of the same user do not overlap.
- A query should run in sub-linear time in the total number of trips.
Examples
Example 1
Input: locate_traveler(['__init__', 'get_airport', 'get_airport', 'get_airport'], [[[['Alice', 'JFK', 10, 20], ['Alice', 'LAX', 30, 40], ['Bob', 'SFO', 15, 25]]], ['Alice', 15], ['Alice', 25], ['Bob', 20]])
Output: [None, 'JFK', None, 'SFO']
Example 2
Input: locate_traveler(['__init__', 'get_airport', 'get_airport'], [[[['u', 'A', 1, 2]]], ['u', 1], ['u', 2]])
Output: [None, 'A', 'A']
Hints
Hint 1
Only the queried user's trips matter, so group all trips by user in a dictionary.
Hint 2
After sorting one user's trips by start time, at most one trip can contain a given timestamp: the last trip that starts at or before it.
Hint 3
Use bisect_right on the list of start times to find that candidate, then check that the timestamp is no later than its end time. Build the start-time lists once per load, not once per query.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each query concerns a single user, so the first step is to group trips by user in a dictionary. For each user, sort the trips by start time and keep a separate list containing only the start times.
To answer a query for time t:
- Look up the user's trips. If there are none, the answer is
None. - Use
bisect_righton the start-time list. The result minus one is the index of the last trip whose start is at or beforet. - If that index is valid and
tis no later than that trip's end time, return its airport. Otherwise returnNone.
The start-time lists are built once when the data is loaded, not on every query, so each query really is logarithmic.
Why it is correct
- Every trip after the candidate starts after
t, so none of them can containt. - Every trip before the candidate ends before the candidate starts (trips don't overlap), and the candidate starts at or before
t. So none of those can containteither. - That leaves the candidate as the only possible match, and the end-time check decides whether it actually covers
t. bisect_rightcounts a trip starting exactly attas a candidate, and the<=comparison on the end time includes the end boundary. Together they implement the closed interval.- An unknown user, a timestamp before the first trip, a timestamp in a gap, and a timestamp after the last trip all produce
None. - A second
"__init__"rebuilds both dictionaries from scratch, so old data is discarded.
Complexity
Let N be the number of trips in a load and k the number of trips for the queried user.
- Loading:
O(N log N)for grouping and sorting. - Each query:
O(log k). - Space:
O(N).
Reference solution
from bisect import bisect_right
from collections import defaultdict
from typing import List
def locate_traveler(operations: List[str], arguments: List[List]) -> List:
trips_by_user = {}
starts_by_user = {}
results = []
for operation, args in zip(operations, arguments):
if operation == "__init__":
grouped = defaultdict(list)
for user_id, airport_code, start_time, end_time in args[0]:
grouped[user_id].append((start_time, end_time, airport_code))
trips_by_user = {}
starts_by_user = {}
for user_id, user_trips in grouped.items():
user_trips.sort()
trips_by_user[user_id] = user_trips
starts_by_user[user_id] = [t[0] for t in user_trips]
results.append(None)
elif operation == "get_airport":
user_id, timestamp = args
trips = trips_by_user.get(user_id)
if not trips:
results.append(None)
continue
index = bisect_right(starts_by_user[user_id], timestamp) - 1
if index >= 0 and timestamp <= trips[index][1]:
results.append(trips[index][2])
else:
results.append(None)
else:
raise ValueError("Unknown operation: " + str(operation))
return results