KatInterview

Track Click-to-Conversion Matching with Time Windows

Data Structure DesignAuto-graded · 20 test cases
MediumAuto-gradedData Structure Designqueueshash-mapstime-windows

Last updated

Tests event stream processing with time-based lookback windows, requiring efficient per-user state management and timestamp-based expiration logic.

You are building a system to match user clicks with conversion events. The system processes a chronological stream of events, where each event is either a CLICK or a CONVERSION for a particular user at a specific timestamp.

Your task is to match conversions to clicks according to these rules:

  • When a CONVERSION event arrives for a user, it should match the most recent CLICK event for that same user that occurred within a lookback window
  • The lookback window extends from conversion_timestamp - lookback_window_ms to conversion_timestamp (inclusive on both ends)
  • Each CLICK can only be matched once; after a click is consumed by a conversion, it becomes unavailable
  • If no valid click exists within the window, the conversion remains unmatched

Implement the function match_conversion_events that processes a sequence of events and returns a result for each event:

  • For CLICK events: return -1
  • For CONVERSION events: return the user_id if a matching click was found and consumed, otherwise return -1

Input:

  • lookback_window_ms: an integer representing the maximum time difference (in milliseconds) for a valid match
  • operations: a list of event types, each either "CLICK" or "CONVERSION"
  • arguments: a list where each element is [user_id, timestamp] corresponding to each operation

Output:

  • A list of integers, one result per event in order

Constraints:

  • Events arrive in non-decreasing timestamp order
  • 1 ≤ lookback_window_ms ≤ 10^9
  • 1 ≤ number of events ≤ 10^6
  • 1 ≤ user_id ≤ 10^9
  • 0 ≤ timestamp ≤ 10^15
  • All inputs are valid integers

Examples

Example 1

Input: match_conversion_events(1000, ['CLICK', 'CONVERSION', 'CONVERSION'], [[1, 1000], [1, 1500], [1, 2500]])

Output: [-1, 1, -1]

Example 2

Input: match_conversion_events(500, ['CLICK', 'CLICK', 'CONVERSION', 'CONVERSION'], [[7, 10], [7, 20], [7, 20], [7, 20]])

Output: [-1, -1, 7, 7]

Hints

Hint 1

Maintain separate state for each user to track their click history

Hint 2

Since events arrive in timestamp order, older clicks that fall outside the window can be safely discarded

Hint 3

A deque allows efficient removal from both ends: prune expired clicks from the front, consume the latest click from the back