Find Consecutive Integers from a Data Stream - Problem
Data Stream Consecutive Checker
Imagine you're monitoring a data stream in real-time and need to detect when a specific pattern occurs. Your task is to implement a
The class should support:
•
•
Key Point: If fewer than
Example:
Imagine you're monitoring a data stream in real-time and need to detect when a specific pattern occurs. Your task is to implement a
DataStream class that tracks whether the last k integers in the stream are all equal to a target value.The class should support:
•
DataStream(int value, int k) - Initialize with target value and window size k•
boolean consec(int num) - Add num to stream and return true if the last k numbers all equal the target valueKey Point: If fewer than
k numbers have been processed, always return false.Example:
DataStream ds = new DataStream(4, 3);ds.consec(4); // false (only 1 number, need 3)ds.consec(4); // false (only 2 numbers, need 3)ds.consec(4); // true (last 3 numbers are all 4)ds.consec(3); // false (last 3 numbers: 4,4,3) Input & Output
example_1.py — Basic Usage
$
Input:
DataStream(4, 3)
consec(4) → consec(4) → consec(4) → consec(3)
›
Output:
[false, false, true, false]
💡 Note:
First two calls return false (need 3 numbers). Third call returns true (last 3 are all 4). Fourth call returns false (last 3 are 4,4,3).
example_2.py — Reset Pattern
$
Input:
DataStream(1, 4)
consec(1) → consec(1) → consec(1) → consec(2) → consec(1) → consec(1) → consec(1) → consec(1)
›
Output:
[false, false, false, false, false, false, false, true]
💡 Note:
Counter resets to 0 when 2 appears, then rebuilds. Need 4 consecutive 1's to return true.
example_3.py — k=1 Edge Case
$
Input:
DataStream(5, 1)
consec(5) → consec(3) → consec(5)
›
Output:
[true, false, true]
💡 Note:
With k=1, every number that matches the target immediately returns true.
Visualization
Tap to expand
Understanding the Visualization
1
Package Arrives
New number enters the data stream
2
Quality Check
Compare with target value - match or not?
3
Update Counter
Increment streak counter or reset to 0
4
Alert Decision
Trigger alert if consecutive count reaches k
Key Takeaway
🎯 Key Insight: We don't need to store the entire stream history - just count consecutive matches!
Time & Space Complexity
Time Complexity
O(1)
Each consec() call does constant work - just update counter
✓ Linear Growth
Space Complexity
O(1)
Only store target value, k, and consecutive count
✓ Linear Space
Constraints
- 1 ≤ value, num ≤ 109
- 1 ≤ k ≤ 105
- At most 105 calls to consec
- Time limit: 1000ms per test case
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code