Count Valid Highway Trips
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Automated highway gantries emit scan dictionaries whenever a vehicle passes an on-ramp ("ENTRY") or an off-ramp ("EXIT"). Because scans arrive from independent roadside readers, the combined list records can appear in any order.
Each dictionary in records has three keys:
'vehicle_id'(str): identifier of the scanned vehicle.'type'(str): either'ENTRY'or'EXIT'.'timestamp'(int): integer clock reading when the scan occurred.
Two scan records form a completed journey when all three criteria hold:
- Both scans carry the exact same
'vehicle_id'. - One scan has
'type': 'ENTRY', the other has'type': 'EXIT', and the'ENTRY'timestamp is strictly smaller than the'EXIT'timestamp. - No other scan belonging to that same
'vehicle_id'has a timestamp strictly between the two timestamps.
Implement count_completed_journeys(records) to return the total number of completed journeys across all vehicles.
Examples
Example 1
Input: records = [
{"vehicle_id": "V1", "type": "ENTRY", "timestamp": 12},
{"vehicle_id": "V2", "type": "ENTRY", "timestamp": 4},
{"vehicle_id": "V1", "type": "EXIT", "timestamp": 30},
{"vehicle_id": "V2", "type": "ENTRY", "timestamp": 18},
{"vehicle_id": "V2", "type": "EXIT", "timestamp": 27},
{"vehicle_id": "V2", "type": "EXIT", "timestamp": 40}
]
Output: 2
Vehicle "V1" enters at 12 and exits at 30 with no other "V1" scans in between (scans from "V2" do not interfere), giving 1 trip. Vehicle "V2" has chronological scans ENTRY@4, ENTRY@18, EXIT@27, EXIT@40; only (18, 27) has no "V2" scan between its endpoints, adding 1 more trip for a total of 2.
Example 2
Input: records = [
{"vehicle_id": "truck-9", "type": "EXIT", "timestamp": 50},
{"vehicle_id": "truck-9", "type": "EXIT", "timestamp": 14},
{"vehicle_id": "truck-9", "type": "ENTRY", "timestamp": 35},
{"vehicle_id": "truck-9", "type": "ENTRY", "timestamp": 8}
]
Output: 2
Ordering "truck-9"'s scans by timestamp yields ENTRY@8, EXIT@14, ENTRY@35, EXIT@50. Both (8, 14) and (35, 50) are uninterrupted ENTRY -> EXIT pairs, so the total count is 2.
Constraints
0 <= len(records) <= 10^5- Every
record['type']is either'ENTRY'or'EXIT'. - All timestamps belonging to the same
'vehicle_id'are distinct integers (different vehicles may share identical timestamps).
Step-by-step walkthrough
Understand what makes a journey valid
Each scan dictionary looks like
{"vehicle_id": "V1", "type": "ENTRY", "timestamp": 12}, and the input list arrives in arbitrary order. We want to count how many pairs(entry_scan, exit_scan)satisfy all three conditions:- Same vehicle: both dictionaries carry the same
vehicle_id. - Forward in time:
entry_scan["timestamp"] < exit_scan["timestamp"]. - Nothing in between for that car: no third scan of the same
vehicle_idhas a timestamp strictly between them.
Look closely at Condition 3 on Vehicle
"V2"in Example 1:Vehicle V2's scans: ENTRY @ 4 ENTRY @ 18 EXIT @ 27 EXIT @ 40 |--------- blocked by 18 ---------| |---- valid (1) ---| |-------------- blocked by 18 and 27 -------------|Even though
"V2"entered at4and exited at27(and40), neither(4, 27)nor(4, 40)counts because"V2"has intermediate scans in between. Meanwhile, scans belonging to"V1"never block"V2".- Same vehicle: both dictionaries carry the same
Why brute force and stack matching both miss the mark
Two tempting ideas fail here for very different reasons:
- Pairwise brute force is too slow: trying every
ENTRY, pairing it with every laterEXITof the same vehicle, and scanning for a blocker in between takes three nested loops —O(n^3)time. Withn = 100,000records, evenO(n^2)is10,000,000,000operations. - A "parentheses stack" gives wrong answers: pushing each
ENTRYonto a stack and popping whenever anEXITarrives fails right away on"V2"from Example 1:
Timeline: ENTRY @ 4 ENTRY @ 18 EXIT @ 27 EXIT @ 40 Stack idea: | |--- pairs (18, 27) ---| | |---------------- pairs (4, 40) WRONG! ---------| (18 and 27 sit between 4 and 40!)Only
(18, 27)has nothing between its timestamps, so the true count for"V2"is1, whereas a stack reports2.- Pairwise brute force is too slow: trying every
Key insight: "nothing in between" means adjacent after sorting
Once we isolate one vehicle's scans and sort them by
timestamp, unique per-vehicle timestamps give a strictly increasing timelinet_0 < t_1 < t_2 < ....When do two scans in a sorted list have zero other scans between them? Precisely when they sit immediately next to each other at indices
i - 1andi!Adjacent pair in sorted order Valid journey? --------------------------------- ------------------------------------------- (12, ENTRY) -> (30, EXIT) YES: ENTRY followed immediately by EXIT ( 4, ENTRY) -> (18, ENTRY) NO: two entries in a row (missed exit) (14, EXIT) -> (35, ENTRY) NO: gap between one trip ending and next starting (27, EXIT) -> (40, EXIT) NO: two exits in a row (missed entry)Also, because each scan has only one immediate right neighbor, no
ENTRYorEXITcan ever be double-counted across two trips.Group scans by vehicle
We scan
recordsonce and populatevehicle_events, mapping eachvehicle_idto its list of(timestamp, gate_type)tuples. Placingtimestampfirst in each tuple ensures Python's built-in.sort()orders tuples chronologically.def group_by_vehicle(records: List[Dict[str, object]]) -> Dict[object, List[Tuple[int, str]]]: """Group toll scans by vehicle_id into lists of (timestamp, gate_type) tuples.""" # vehicle_events: maps vehicle_id -> [(timestamp, gate_type), ...] # e.g. {"V1": [(12, "ENTRY"), (30, "EXIT")]} vehicle_events: Dict[object, List[Tuple[int, str]]] = {} for record in records: vehicle_id = record["vehicle_id"] if vehicle_id not in vehicle_events: vehicle_events[vehicle_id] = [] # Put timestamp first so Python's tuple sort orders events chronologically. vehicle_events[vehicle_id].append((record["timestamp"], record["type"])) return vehicle_eventsSort each timeline and count adjacent pairs
For every vehicle, we sort its
eventslist in ascending timestamp order and inspect every neighbor pair(events[i - 1], events[i])forifrom1tolen(events) - 1. Unpacking(prev_time, prev_type)and(curr_time, curr_type)makes the check crystal clear, andprev_time < curr_timedirectly guards Condition 2.Let's trace both examples to see the data flow:
Example 1: Vehicle "V1" sorted: [(12, "ENTRY"), (30, "EXIT")] i = 1: (12, "ENTRY") -> (30, "EXIT") ==> +1 journey Vehicle "V2" sorted: [(4, "ENTRY"), (18, "ENTRY"), (27, "EXIT"), (40, "EXIT")] i = 1: ( 4, "ENTRY") -> (18, "ENTRY") ==> skip i = 2: (18, "ENTRY") -> (27, "EXIT") ==> +1 journey i = 3: (27, "EXIT") -> (40, "EXIT") ==> skip Total = 2 Example 2 (arrives out of order): Vehicle "truck-9" sorted: [(8, "ENTRY"), (14, "EXIT"), (35, "ENTRY"), (50, "EXIT")] i = 1: ( 8, "ENTRY") -> (14, "EXIT") ==> +1 journey i = 2: (14, "EXIT") -> (35, "ENTRY") ==> skip (between trips) i = 3: (35, "ENTRY") -> (50, "EXIT") ==> +1 journey Total = 2Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def group_by_vehicle(records: List[Dict[str, object]]) -> Dict[object, List[Tuple[int, str]]]: """Group toll scans by vehicle_id into lists of (timestamp, gate_type) tuples.""" # vehicle_events: maps vehicle_id -> [(timestamp, gate_type), ...] # e.g. {"V1": [(12, "ENTRY"), (30, "EXIT")]} vehicle_events: Dict[object, List[Tuple[int, str]]] = {} for record in records: vehicle_id = record["vehicle_id"] if vehicle_id not in vehicle_events: vehicle_events[vehicle_id] = [] # Put timestamp first so Python's tuple sort orders events chronologically. vehicle_events[vehicle_id].append((record["timestamp"], record["type"])) return vehicle_events def count_completed_journeys(records: List[Dict[str, object]]) -> int: # Phase 1: Isolate each vehicle's scans so other cars' events never interfere. vehicle_events = group_by_vehicle(records) completed_journeys = 0 for events in vehicle_events.values(): # Phase 2: Sort this vehicle's events in ascending timestamp order. events.sort() # Phase 3: Once sorted, "no scan of this vehicle in between" means the # ENTRY and EXIT must sit at consecutive indices in `events`. for i in range(1, len(events)): prev_time, prev_type = events[i - 1] curr_time, curr_type = events[i] # Enforce strictly smaller ENTRY timestamp (rule 2) and ENTRY -> EXIT order. if prev_type == "ENTRY" and curr_type == "EXIT" and prev_time < curr_time: completed_journeys += 1 return completed_journeys✅ Submit now — all tests should pass.
Intuition & how it works
Imagine dumping a box full of shuffled paper toll slips onto a table. Right now, slips from thousands of vehicles and timestamps are mixed together. If you first deal the slips into one small stack per license plate using a hash map (a key-value lookup dictionary, called dict in Python), and then spread each vehicle's slips left-to-right in ascending timestamp order, the "no intermediate scan for that vehicle" requirement becomes effortless: two slips have nothing between them if and only if they sit immediately side by side. You simply count how many neighbor pairs read ENTRY on the left and EXIT on the right.
More obvious strategies stumble quickly. Testing every (ENTRY, EXIT) pair and scanning the input to verify nothing sits between them takes O(n^3) time, which times out well before n = 100,000. Sorting all records together by timestamp alone interleaves different vehicles, letting "V2"'s scans split up "V1"'s valid trip. And matching entries with a stack (like balanced parentheses) pairs outer scans in ENTRY@4, ENTRY@18, EXIT@27, EXIT@40 even though 18 and 27 lie strictly between 4 and 40.
Walk through Example 1 to see how clean per-vehicle sorting is:
1. Grouping puts "V1"'s scans into [(12, "ENTRY"), (30, "EXIT")] and "V2"'s scans into [(4, "ENTRY"), (18, "ENTRY"), (27, "EXIT"), (40, "EXIT")].
2. Sorting "V1"'s list gives [(12, "ENTRY"), (30, "EXIT")]; its neighbor pair (12 -> 30) is ENTRY -> EXIT, adding 1.
3. Sorting "V2"'s list gives [(4, "ENTRY"), (18, "ENTRY"), (27, "EXIT"), (40, "EXIT")]; (4 -> 18) is ENTRY -> ENTRY (skipped), (18 -> 27) is ENTRY -> EXIT (adds 1), and (27 -> 40) is EXIT -> EXIT (skipped), giving 2 in total.
Complexity
- Time: O(n log n), where
nis the total number of scan records. Grouping into dictionary lists takes oneO(n)pass withO(1)average hash lookups; if vehicleihask_iscans (withk_1 + k_2 + ... = n), sorting all per-vehicle lists costssum(k_i log k_i) <= sum(k_i log n) = n log n; and checking adjacent pairs visits each scan once more inO(n)time. - Space: O(n). Every input scan is stored once as a
(timestamp, gate_type)tuple insidevehicle_events, using memory proportional to the number of records.
Edge cases
- Empty list or single record:
range(1, len(events))is empty for lists of length0or1, returning0cleanly. - Scans arriving out of chronological order: Example 2 provides
EXIT@50, EXIT@14, ENTRY@35, ENTRY@8; sorting restoresENTRY@8 -> EXIT@14 -> ENTRY@35 -> EXIT@50and counts2. - Chronologically reversed gates (
EXIT@1thenENTRY@2): After sorting, the neighbor pair isEXIT -> ENTRY(leaving one highway trip and later starting another), which rightly counts0. - Nested sensor glitches (
ENTRY@4, ENTRY@18, EXIT@27, EXIT@40): Neighbor pairs areENTRY->ENTRY,ENTRY->EXIT, andEXIT->EXIT, so only(18, 27)counts (1). - Multiple completed trips by one vehicle:
ENTRY@8, EXIT@14, ENTRY@35, EXIT@50has twoENTRY -> EXITneighbor transitions and counts2. - Equal timestamps across different vehicles:
"A"entering att = 5and"B"entering att = 5live in separate dictionary lists and never collide.
Common mistakes
- Using a stack or counting
min(entries, exits)per vehicle: Both approaches pairENTRY@4withEXIT@40inENTRY@4, ENTRY@18, EXIT@27, EXIT@40, wrongly returning2instead of1. (A single "immediately preceding event type" variable after sorting does work because it only remembers the direct predecessor.) - Sorting all records by
timestampalone: A scan from"V2"att = 18then sits between"V1"'sENTRY@12andEXIT@30and hides"V1"'s trip. - Scanning neighbors without sorting first: Input records arrive in arbitrary order, so input-array neighbors are not chronological neighbors.
- Putting
typebeforetimestampin the tuple: Sorting("ENTRY", 35)and("EXIT", 14)orders alphabetically by"ENTRY" < "EXIT"instead of chronologically by14 < 35. - Using
<=instead of<on timestamps: Condition 2 requires theENTRYtimestamp to be strictly smaller than theEXITtimestamp (prev_time < curr_time).
Alternative approaches
- Single global sort by
(vehicle_id, timestamp): Instead of building a hash map, sort a flat list of(vehicle_id, timestamp, type)tuples once and count adjacent elements that share the samevehicle_idand transitionENTRY -> EXIT. Time remainsO(n log n)with slightly lower dictionary overhead, thoughvehicle_idstrings are compared during sorting.
Follow-up questions
- How would you adapt this algorithm if toll events arrived continuously over a live stream instead of a fixed batch? If events for each vehicle arrive strictly in timestamp order, keep a map from
vehicle_idto its single most recent event type: whenever anEXITarrives for a vehicle whose previous state wasENTRY, increment the completed-trip counter and flip its state toEXITinO(1)time. When network delays can deliver scans out of order, buffer each vehicle's recent events in a small timestamp-ordered window and advance a watermark (a moving timestamp threshold behind which late arrivals are no longer expected), scoring and evicting events once the watermark passes them. - How should a production system treat unmatched EXIT events when a sensor misses the earlier ENTRY scan? On a sorted per-vehicle timeline, an unmatched exit appears either as the vehicle's very first event or as an
EXITimmediately following anotherEXIT. Whilecount_completed_journeysskips them, a real tolling pipeline should route unmatched exits to an operational alert stream and dead-letter queue so maintenance crews can pinpoint faulty on-ramp readers and billing rules can apply a configured fallback fare (such as the minimum plaza toll). - How could you keep memory usage bounded while tracking state for millions of active vehicles? Only store keys for vehicles whose latest scan is
ENTRY— as soon as anEXITarrives, delete thatvehicle_idfrom the map so memory scales with vehicles currently driving rather than historical traffic. Add a TTL (time-to-live) (an automatic expiration window, such as 24 hours) to evict stale entries from missed exit scans, encode IDs and timestamps as compact fixed-width integers instead of Python dictionaries, and apply sharding (partitioning keys across worker nodes viahash(vehicle_id) % num_shards) so each worker holds a small fraction of active vehicles.
Follow-up questions
- How would you adapt this algorithm if toll events arrived continuously over a live stream instead of a fixed batch?
- How should a production system treat unmatched EXIT events when a sensor misses the earlier ENTRY scan?
- How could you keep memory usage bounded while tracking state for millions of active vehicles?
Similar questions
- Hardware Device Registry: Validation, Active Tallies, and Bulk Transitions
- Real-Time Multi-Server Channel Chat Service
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance