Find Consecutive Integers from a Data Stream - Problem
For a stream of integers, implement a data structure that checks if the last k integers parsed in the stream are equal to value.
Implement the DataStream class:
DataStream(int value, int k)Initializes the object with an empty integer stream and the two integersvalueandk.boolean consec(int num)Addsnumto the stream of integers. Returnstrueif the lastkintegers are equal tovalue, andfalseotherwise. If there are less thankintegers, the condition does not hold true, so returnsfalse.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["DataStream", "consec", "consec", "consec", "consec"], params = [[4, 3], [4], [3], [5], [4]]
›
Output:
[null, false, false, false, false]
💡 Note:
Initialize with value=4, k=3. Add 4 (count=1<3, false), add 3 (count=0<3, false), add 5 (count=0<3, false), add 4 (count=1<3, false)
Example 2 — Consecutive Match
$
Input:
operations = ["DataStream", "consec", "consec", "consec", "consec"], params = [[4, 3], [4], [4], [4], [3]]
›
Output:
[null, false, false, true, false]
💡 Note:
After three consecutive 4s, count=3≥k=3 returns true. Adding 3 resets count=0, returns false
Example 3 — Edge Case k=1
$
Input:
operations = ["DataStream", "consec", "consec"], params = [[5, 1], [5], [6]]
›
Output:
[null, true, false]
💡 Note:
With k=1, first matching number immediately returns true. Non-matching number returns false
Constraints
- 1 ≤ value ≤ 109
- 1 ≤ k ≤ 105
- 1 ≤ num ≤ 109
- At most 105 calls to consec
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Create DataStream with target value=4 and k=3
2
Process Stream
Add numbers one by one, track consecutive matches
3
Return Result
True when k consecutive numbers match target value
Key Takeaway
🎯 Key Insight: Track consecutive count with O(1) space instead of storing all numbers
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code