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 integers value and k.
  • boolean consec(int num) Adds num to the stream of integers. Returns true if the last k integers are equal to value, and false otherwise. If there are less than k integers, the condition does not hold true, so returns false.

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
DataStream: Find K Consecutive IntegersTarget: value=4, k=3Input Stream:4354442Consecutive Count:1001230Return Value:falsefalsefalsefalsefalsetruefalse
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
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
18.4K Views
Medium Frequency
~15 min Avg. Time
385 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen