You are given a list of delivery events for multiple orders, in the order they happened. Determine whether the sequence is valid.
Each event is a list [action, order_id], where action is either "Pickup" or "Dropoff" and order_id is a string identifier for the order.
A sequence is valid if no order is dropped off before it has been picked up. Return True if the sequence is valid and False otherwise.
Function Signature
def is_valid_path(events: list[list[str]]) -> bool:
Rules
-
A
"Dropoff"
of an order is valid only if that order is currently being carried, meaning it has been picked up and not yet dropped off since that pickup.
-
After a dropoff, the order is no longer carried. A second
"Dropoff"
of the same order is invalid unless another
"Pickup"
of it happens in between.
-
A
"Pickup"
of an order that is already being carried has no effect. The order is still carried once, and one
"Dropoff"
delivers it.
-
An order may be picked up again after it has been delivered.
-
Orders that are picked up and never dropped off do not make the sequence invalid.
-
Order IDs are compared as exact strings, so
"1"
and
"01"
are different orders.
Constraints
-
1 <= len(events) <= 10^5
-
Each event is a list
[action, order_id]
-
action
is either
"Pickup"
or
"Dropoff"
-
order_id
is a non-empty string
Examples
Input: events = [["Pickup","1"], ["Pickup","2"], ["Dropoff","1"], ["Dropoff","2"]]
Output: True
Order 1 is picked up, then order 2. Each order is being carried at the moment it is dropped off, so the sequence is valid.
Input: events = [["Pickup","1"], ["Dropoff","2"], ["Pickup","2"], ["Dropoff","1"]]
Output: False
Order 2 is dropped off at the second event, before its pickup at the third event.
Input: events = [["Pickup","A"], ["Pickup","B"], ["Dropoff","A"], ["Dropoff","A"]]
Output: False
The first dropoff of A is fine. The second one happens after A was already delivered and not picked up again. Order B is never dropped off, which on its own would not make the sequence invalid.