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:

  1. Both scans carry the exact same 'vehicle_id'.
  2. One scan has 'type': 'ENTRY', the other has 'type': 'EXIT', and the 'ENTRY' timestamp is strictly smaller than the 'EXIT' timestamp.
  3. 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

  1. 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:

    1. Same vehicle: both dictionaries carry the same vehicle_id.
    2. Forward in time: entry_scan["timestamp"] < exit_scan["timestamp"].
    3. Nothing in between for that car: no third scan of the same vehicle_id has 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 at 4 and exited at 27 (and 40), neither (4, 27) nor (4, 40) counts because "V2" has intermediate scans in between. Meanwhile, scans belonging to "V1" never block "V2".

  2. 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 later EXIT of the same vehicle, and scanning for a blocker in between takes three nested loops — O(n^3) time. With n = 100,000 records, even O(n^2) is 10,000,000,000 operations.
    • A "parentheses stack" gives wrong answers: pushing each ENTRY onto a stack and popping whenever an EXIT arrives 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" is 1, whereas a stack reports 2.

  3. 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 timeline t_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 - 1 and i!

    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 ENTRY or EXIT can ever be double-counted across two trips.

  4. Group scans by vehicle

    We scan records once and populate vehicle_events, mapping each vehicle_id to its list of (timestamp, gate_type) tuples. Placing timestamp first 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_events
    
  5. Sort each timeline and count adjacent pairs

    For every vehicle, we sort its events list in ascending timestamp order and inspect every neighbor pair (events[i - 1], events[i]) for i from 1 to len(events) - 1. Unpacking (prev_time, prev_type) and (curr_time, curr_type) makes the check crystal clear, and prev_time < curr_time directly 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 = 2
    
  6. Complete 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 n is the total number of scan records. Grouping into dictionary lists takes one O(n) pass with O(1) average hash lookups; if vehicle i has k_i scans (with k_1 + k_2 + ... = n), sorting all per-vehicle lists costs sum(k_i log k_i) <= sum(k_i log n) = n log n; and checking adjacent pairs visits each scan once more in O(n) time.
  • Space: O(n). Every input scan is stored once as a (timestamp, gate_type) tuple inside vehicle_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 length 0 or 1, returning 0 cleanly.
  • Scans arriving out of chronological order: Example 2 provides EXIT@50, EXIT@14, ENTRY@35, ENTRY@8; sorting restores ENTRY@8 -> EXIT@14 -> ENTRY@35 -> EXIT@50 and counts 2.
  • Chronologically reversed gates (EXIT@1 then ENTRY@2): After sorting, the neighbor pair is EXIT -> ENTRY (leaving one highway trip and later starting another), which rightly counts 0.
  • Nested sensor glitches (ENTRY@4, ENTRY@18, EXIT@27, EXIT@40): Neighbor pairs are ENTRY->ENTRY, ENTRY->EXIT, and EXIT->EXIT, so only (18, 27) counts (1).
  • Multiple completed trips by one vehicle: ENTRY@8, EXIT@14, ENTRY@35, EXIT@50 has two ENTRY -> EXIT neighbor transitions and counts 2.
  • Equal timestamps across different vehicles: "A" entering at t = 5 and "B" entering at t = 5 live in separate dictionary lists and never collide.

Common mistakes

  • Using a stack or counting min(entries, exits) per vehicle: Both approaches pair ENTRY@4 with EXIT@40 in ENTRY@4, ENTRY@18, EXIT@27, EXIT@40, wrongly returning 2 instead of 1. (A single "immediately preceding event type" variable after sorting does work because it only remembers the direct predecessor.)
  • Sorting all records by timestamp alone: A scan from "V2" at t = 18 then sits between "V1"'s ENTRY@12 and EXIT@30 and hides "V1"'s trip.
  • Scanning neighbors without sorting first: Input records arrive in arbitrary order, so input-array neighbors are not chronological neighbors.
  • Putting type before timestamp in the tuple: Sorting ("ENTRY", 35) and ("EXIT", 14) orders alphabetically by "ENTRY" < "EXIT" instead of chronologically by 14 < 35.
  • Using <= instead of < on timestamps: Condition 2 requires the ENTRY timestamp to be strictly smaller than the EXIT timestamp (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 same vehicle_id and transition ENTRY -> EXIT. Time remains O(n log n) with slightly lower dictionary overhead, though vehicle_id strings 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_id to its single most recent event type: whenever an EXIT arrives for a vehicle whose previous state was ENTRY, increment the completed-trip counter and flip its state to EXIT in O(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 EXIT immediately following another EXIT. While count_completed_journeys skips 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 an EXIT arrives, delete that vehicle_id from 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 via hash(vehicle_id) % num_shards) so each worker holds a small fraction of active vehicles.

Follow-up questions

Similar questions

More Onepay interview questions

All 3 Onepay questions →