KatInterview

Filter Stream Events by Registered Patterns

Data Structure DesignAuto-graded · 25 test cases
MediumAuto-gradedData Structure Designhash-tablessetsinverted-index

Last 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.