Katkat

Convert State Stream to Events

AnthropicMachine Learning Engineer · Onsite

Last updated

This question tests the ability to process a stream of state changes, group consecutive identical values into distinct event intervals, and filter these events based on duration.

Problem Statement

You are monitoring a system that outputs a continuous stream of state readings over time. A "state" is defined as a categorical value (e.g., "ACTIVE", "IDLE", "ERROR"). You are given a list of dictionaries where each entry contains a timestamp (integer) and a state (string).

Consecutive readings with the same state represent a continuous duration of that state. An "event" is defined as a contiguous block of one or more identical states, characterized by its state, start_time, and end_time (the timestamp of the last reading before the state changes).

Write a function extract_events(readings, min_duration) that returns a list of events. An event should only be included in the output if its duration (end_time - start_time) is greater than or equal to min_duration.

Function Signature

def extract_events(readings, min_duration):
    # readings: list of dicts {'timestamp': int, 'state': str}
    # min_duration: int
    # returns: list of dicts {'state': str, 'start_time': int, 'end_time': int}

Examples

Example 1: Input:

readings = [
    {'timestamp': 1, 'state': 'A'}, {'timestamp': 2, 'state': 'A'}, 
    {'timestamp': 3, 'state': 'B'}, {'timestamp': 4, 'state': 'B'}, 
    {'timestamp': 5, 'state': 'B'}
]
min_duration = 2

Output: [{'state': 'A', 'start_time': 1, 'end_time': 2}, {'state': 'B', 'start_time': 3, 'end_time': 5}] (Event A duration: 2-1=1. Wait, if min_duration is 2, A is excluded. Output: [{'state': 'B', 'start_time': 3, 'end_time': 5}])

Constraints

  • readings is sorted by timestamp.
  • readings length: 0 to 10^5.
  • All timestamps are non-negative integers.

Edge Cases

  • Empty input list.
  • A single reading list.
  • All readings having the same state.
  • min_duration being 0.

Hints

Hint 1

Iterate through the sorted readings and keep track of the current event's start time and current state.

Hint 2

When the state changes or you reach the end of the input list, finalize the current event and check if its duration meets the threshold.

Hint 3

Use a single pass approach to maintain O(n) time complexity and O(1) auxiliary space (excluding output).

Follow-up questions

  • How would you modify your solution if the input `readings` were not guaranteed to be sorted by timestamp?
  • What changes are needed if you receive the data as an infinite iterator rather than a list?
  • How would you handle gaps in timestamps (e.g., if a state persists for 10 seconds but we only have readings at t=0 and t=10)?