Subscription Filter Matching with Ordered Delivery
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a message router that matches nested JSON events against per-queue filter policies and returns matching queues in first-subscription order.
You are simulating a small in-memory message router. Queues register a filter policy, and each incoming event is delivered to every queue whose policy it satisfies.
Because the judge calls a single function, the router is driven by a script of commands. operations[i] is the command name and arguments[i] is the list of arguments for that command. Process the commands in order and return one result per command.
Commands
"subscribe"with arguments[queue_id, filter_policy]- Stores
filter_policyforqueue_id. - If
queue_idis new, it goes to the end of the subscription order. - If
queue_idalready exists, only its policy is replaced and its position in the order stays as it was. - Result for this command:
None.
- Stores
"route"with arguments[event]- Result: the list of
queue_ids whose current policy matchesevent, in subscription order (the order in which each queue was first subscribed). Return[]if nothing matches.
- Result: the list of
Filter policies
A policy is a dictionary mapping a field path to a condition. An event matches a policy only if every entry is satisfied. A policy with no entries matches every event.
Field paths. A path such as "user.address.city" is split on . and followed through nested dictionaries in the event. If any step is missing, or the value reached at some step is not a dictionary, the field is absent and its condition fails. A field that is present with the value null (None) exists, but it satisfies none of the condition types below.
Condition types. The condition for a field is one of the following.
- Value list. A list of primitives (
str,int,float,bool). The condition holds if the field equals at least one entry. An empty list never matches. Equality is type-aware:- Booleans are only equal to booleans (
trueis not1, andfalseis not0). - Numbers compare by numeric value, so
100equals100.0. - Strings only equal strings.
- A field holding a list, a dictionary or
nullnever equals any entry.
- Booleans are only equal to booleans (
- Numeric bounds. A dictionary using any of
"$gt","$gte","$lt","$lte". The field value must be a real number (intorfloat, not a boolean), and it must satisfy every bound listed. Each bound value must itself be a real number and not a boolean, otherwise the condition fails. - Prefix. A dictionary containing the key
"$prefix". The field value must be a string, the prefix must be a string, and the value must start with the prefix. When"$prefix"is present, only this check is made and other keys in that dictionary are ignored.
Any condition that is neither a list nor a dictionary does not match. If a type does not fit the condition (for example, a numeric bound applied to a string field), the condition is simply not satisfied.
Constraints
- Up to 1,000 distinct queues.
- An event has at most 50 fields and is nested at most 5 levels deep.
- Strings are at most 100 characters long.
- All values are standard JSON types:
dict,list,str,int,float,bool,None. operationsandargumentshave the same length, and every command name is either"subscribe"or"route".
Examples
Example 1
Input: run_router_script(['subscribe', 'subscribe', 'route', 'route'], [['queue-1', {'customer.country': ['US', 'CA'], 'order.total': {'$gte': 100}}], ['queue-2', {'event_id': {'$prefix': 'txn_'}}], [{'event_id': 'txn_98721', 'customer': {'country': 'US'}, 'order': {'total': 150.5}}], [{'event_id': 'audit_001', 'customer': {'country': 'UK'}, 'order': {'total': 200}}]])
Output: [None, None, ['queue-1', 'queue-2'], []]
Example 2
Input: run_router_script(['subscribe', 'subscribe', 'subscribe', 'route'], [['first', {}], ['second', {'kind': ['alert']}], ['first', {'kind': ['alert']}], [{'kind': 'alert'}]])
Output: [None, None, None, ['first', 'second']]
Hints
Hint 1
Keep a mapping from queue id to policy. Python dicts keep insertion order, and assigning to an existing key does not move it, which gives you the required update-in-place behavior.
Hint 2
Write a helper that walks a dotted path through nested dicts and reports failure if a key is missing or the current value is not a dict. Handle a null value correctly: it is present, but matches nothing.
Hint 3
In Python, bool is a subclass of int, so True == 1 and isinstance(True, int) are both true. Add explicit bool checks in both the equality helper and the numeric-bound check.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The work splits into three small pieces.
-
Ordered registry. Keep a dictionary from queue id to policy. Python dictionaries remember insertion order, and assigning to an existing key replaces the value without moving the key. That is exactly the "update in place, keep position" rule, so no extra list is needed.
-
Path resolution. For each policy entry, split the path on
.and walk the event. If a step is not a dictionary or the key is missing, the field is absent and the policy fails. Absence is checked by key membership, so a field that is present with valuenullis treated differently from a missing one. -
Condition evaluation.
- For a value list, use
anyover type-aware equality. - For a prefix condition, check that both the value and the prefix are strings, then use
startswith. - For numeric bounds, check that the value is a real number, check that each bound is a real number, and then apply every comparison present.
A policy matches when all of its entries hold, which is
allover the entries (vacuously true for an empty policy). - For a value list, use
Why it is correct
- Booleans versus numbers. In Python
True == 1andisinstance(True, int)are both true, so without special handling a list[1]would matchtrue, and{"$gt": 0}would matchtrue. The equality helper compares booleans only with booleans, and the numeric check rejects booleans on both the value and the bound. This matches the stated rules. - Ints versus floats. Numbers are compared by value, so
100matches100.0. - Type mismatches. Strings equal only strings, and lists, dicts and
nullnever equal a primitive. A numeric bound on a string, or a prefix on a number, evaluates to false. - Absence. A path through a non-dictionary or a missing key makes the condition fail immediately.
- Order.
routeiterates the registry in insertion order, and updates never change a key's position, so the output is in first-subscription order. - Empty cases. An empty policy matches everything because there is nothing to fail. An empty value list matches nothing because
anyof nothing is false.
Complexity
Let N be the number of subscriptions, F the number of conditions per policy, D the path depth (at most 5) and L the length of the longest value list.
subscribe: O(1).route: O(N * F * (D + L)) in the worst case, which is small for N ≤ 1,000.- Space: O(total size of the stored policies).
Reference solution
from typing import List
def _values_equal(actual, expected):
# JSON booleans are distinct from numbers even though bool subclasses int.
if isinstance(actual, bool) or isinstance(expected, bool):
return (isinstance(actual, bool) and isinstance(expected, bool)
and actual == expected)
if isinstance(actual, (int, float)) and isinstance(expected, (int, float)):
return actual == expected
return type(actual) is type(expected) and actual == expected
def _condition_holds(value, condition):
if isinstance(condition, list):
return any(_values_equal(value, item) for item in condition)
if not isinstance(condition, dict):
return False
if "$prefix" in condition:
prefix = condition["$prefix"]
return (isinstance(value, str) and isinstance(prefix, str)
and value.startswith(prefix))
if isinstance(value, bool) or not isinstance(value, (int, float)):
return False
for op, bound in condition.items():
if isinstance(bound, bool) or not isinstance(bound, (int, float)):
return False
if op == "$gt" and not value > bound:
return False
if op == "$gte" and not value >= bound:
return False
if op == "$lt" and not value < bound:
return False
if op == "$lte" and not value <= bound:
return False
return True
def _policy_holds(event, policy):
for path, condition in policy.items():
value = event
for part in path.split("."):
if not isinstance(value, dict) or part not in value:
return False
value = value[part]
if not _condition_holds(value, condition):
return False
return True
def run_router_script(commands: List[str], payloads: List[List[object]]) -> List[object]:
policies = {} # queue_id -> policy; insertion order = subscription order
results = []
for command, args in zip(commands, payloads):
if command == "subscribe":
queue_id, policy = args
policies[queue_id] = policy
results.append(None)
elif command == "route":
(event,) = args
results.append([q for q, p in policies.items()
if _policy_holds(event, p)])
else:
raise ValueError("Unknown command: " + str(command))
return results