#2526
Find Consecutive Integers from a Data Stream
MediumHash TableDesignQueueCountingData StreamHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of storing all integers, we can maintain a count of consecutive integers equal to the specified value. This allows us to check the condition in constant time.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a counter for consecutive values and a variable to track the total number of integers added.
- 2Step 2: For each new integer, check if it equals the specified value.
- 3Step 3: If it does, increment the counter; if not, reset the counter to zero.
- 4Step 4: If the total count of integers is at least k and the counter equals k, return true; otherwise, return false.
solution.py14 lines
1class DataStream:
2 def __init__(self, value: int, k: int):
3 self.value = value
4 self.k = k
5 self.count = 0
6 self.total = 0
7
8 def consec(self, num: int) -> bool:
9 self.total += 1
10 if num == self.value:
11 self.count += 1
12 else:
13 self.count = 0
14 return self.count == self.k and self.total >= self.kℹ
Complexity note: The time complexity is O(n) because we process each integer once, and the space complexity is O(1) since we only use a few variables to keep track of counts.
- 1Using a counter for consecutive values can significantly reduce time complexity.
- 2Maintaining a total count helps in determining if we have enough integers to check against k.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.