Skip to main content
Problem 32

Extract the Smallest Matching Log Window

HARDBUILD
Two Pointers+3

You're triaging a production incident. The logs from one node contain a sequence of event types, and you need to find the smallest contiguous window of log entries that contains every event type from a required set.

Implement smallest_window(events, required) that returns (start, end) — where events[start:end] is the shortest matching window. If no window matches, return (0, 0).

The judge runs your solution against a 200,000-entry log with sparse coverage and enforces a real time limit. A naive O(n²) sweep won't finish in time.

Requirements
  • Return a (start, end) tuple where end is exclusive — events[start:end] is the matching window.
  • If multiple windows have the same minimum length, return the leftmost one.
  • If no window contains every required event type, return (0, 0).
  • If required is empty, return (0, 0) — an empty requirement is trivially satisfied by an empty window.
  • If required contains duplicates (e.g. ['A', 'A', 'B']), the window must contain at least that many occurrences of each event.
  • Run in O(n) over the events list — the perf test will TLE an O(n²) solution.
Examples
Example 1
Input
events = ['A', 'C', 'B', 'A', 'D', 'B', 'A']
required = ['A', 'B']
Output
(2, 4)
Note

events[2:4] = ['B', 'A'] — smallest window containing both required types.

Example 2
Input
events = ['X', 'X', 'X']
required = ['Y']
Output
(0, 0)
Note

No 'Y' anywhere in the log.

Example 3
Input
events = ['A', 'B', 'A', 'C']
required = ['A', 'A', 'B']
Output
(0, 3)
Note

Need two A's and one B. The window events[0:3] = ['A', 'B', 'A'] satisfies that.

Constraints
  • Do not modify the inputs.
  • Use only the standard library. No NumPy, no external packages.
  • The perf test runs on len(events) up to 200,000 — any algorithm worse than O(n) on the inputs and requirements will exceed the time limit.
Follow-up

How would you change the algorithm if the events were arriving as a stream and you couldn't hold all of them in memory at once?

Hints
Related Practice
Track
Algorithms & Data Structures

Keep moving through related algorithms & data structures problems and build a stronger search-friendly practice loop around this topic.

View track →
Console output will appear here...