Filter Stream Events by Registered Patterns
Data Structure DesignAuto-graded · 25 test casesLast updated
Tests inverted index design and set-based matching to efficiently find which registered word patterns are satisfied by incoming events.
You are processing a stream of events. Each event is a string that starts with either "Q:" or "L:".
- A query event (
"Q:"followed by text) registers a new pattern consisting of space-separated words. Each query is assigned an implicit ID based on arrival order (starting at 0). - A log event (
"L:"followed by text) triggers a search: return the original text of all previously registered queries where every word in that query appears at least once in the log.
Matching rules:
- Words are extracted by splitting on whitespace.
- Matching is case-sensitive.
- A word appearing multiple times in a query or log is treated as appearing once (set semantics).
- A query with no words matches every log.
- A query only matches logs that arrive after the query was registered.
For each log event in the input, collect the matching query texts in the order the queries were registered, and return them as a list. The final output is a list of these per-log results.
Constraints:
- 1 ≤ number of events ≤ 10⁴
- 0 ≤ words per event ≤ 100
- 1 ≤ word length ≤ 50
- All events begin with
"Q:"or"L:" - Words contain printable ASCII characters (no embedded spaces)
Examples
Example 1
Input: filter_stream_events(['Q: error timeout', 'L: request error timeout', 'Q: cache miss', 'L: timeout error error', 'L: cache miss'])
Output: [['error timeout'], ['error timeout'], ['cache miss']]
Example 2
Input: filter_stream_events(['Q: alpha beta', 'L: alpha', 'Q: alpha', 'L: beta alpha', 'L: beta'])
Output: [[], ['alpha beta', 'alpha'], []]
Example 3
Input: filter_stream_events(['Q:', 'L: anything', 'Q: repeated repeated', 'L: repeated'])
Output: [[''], ['', 'repeated repeated']]
Hints
Hint 1
Build an inverted index mapping each word to the list of query IDs that contain it, allowing you to quickly find candidate queries when a log arrives.
Hint 2
For each query, store how many distinct words it contains. A query matches a log when the number of its words found in the log equals this count.
Hint 3
Handle the empty-query edge case separately: queries with zero words should match every log.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is efficiently determining which registered patterns are satisfied by each incoming log without re-scanning all patterns from scratch.
Inverted Index Strategy:
Build a reverse mapping from each word to the list of query IDs that contain it. When a log arrives, iterate over its distinct words, collect all query IDs associated with those words, and count how many of each query's words were found.
Matching Logic:
For each registered query, store its set of distinct words and the size of that set. A query matches a log if and only if the number of its words found in the log equals the total number of distinct words in the query. This ensures every query word appears at least once in the log.
Edge Cases:
- Empty queries (no words after splitting): These have zero distinct words, so the condition
0 == 0is always true. They match every log. - Duplicate words: Using sets eliminates duplicates in both queries and logs automatically.
- Case sensitivity: No normalization is applied;
"Error"and"error"are distinct.
Why It Works:
Each query word is indexed exactly once. For each log, we deduplicate its words and increment a counter for every query that contains each log word. A query is satisfied when all its words have been found, which occurs precisely when the counter equals the query's word count.
Complexity:
Let Q be the number of queries, k be the average query size, L be the average log size, and P be the total number of postings visited per log.
- Time: O(k) per query registration, O(L + P) per log lookup. In the worst case, if all queries share common words, P can approach Q × L, but typical workloads have much sparser overlap.
- Space: O(Q × k) for storing queries and the inverted index.
from collections import defaultdict
from typing import List
def filter_stream_events(lines: List[str]) -> List[List[str]]:
registered_queries = []
query_word_sets = []
word_to_query_ids = defaultdict(list)
output = []
for line in lines:
prefix, content = line[:2], line[2:].strip()
if prefix == "Q:":
words = set(content.split())
query_index = len(registered_queries)
registered_queries.append(content)
query_word_sets.append(words)
for word in words:
word_to_query_ids[word].append(query_index)
elif prefix == "L:":
hit_counts = defaultdict(int)
for word in set(content.split()):
for query_index in word_to_query_ids.get(word, ()):
hit_counts[query_index] += 1
matches = [
registered_queries[idx]
for idx, word_set in enumerate(query_word_sets)
if len(word_set) == hit_counts.get(idx, 0)
]
output.append(matches)
else:
raise ValueError("Each line must begin with 'Q:' or 'L:'")
return output