Skip to content

2526. Find Consecutive Integers from a Data Stream 👍

  • Time: Constructor: $O(1)$, consec(num: int): $O(1)$
  • Space: $O(k)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class DataStream {
 public:
  DataStream(int value, int k) : value(value), k(k) {}

  bool consec(int num) {
    if (q.size() == k) {
      if (q.front() == value)
        --count;
      q.pop();
    }
    if (num == value)
      ++count;
    q.push(num);
    return count == k;
  }

 private:
  const int value;
  const int k;
  queue<int> q;
  int count = 0;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class DataStream {
  public DataStream(int value, int k) {
    this.value = value;
    this.k = k;
  }

  public boolean consec(int num) {
    if (q.size() == k && q.poll() == value)
      --count;
    if (num == value)
      ++count;
    q.offer(num);
    return count == k;
  }

  private int value;
  private int k;
  private Queue<Integer> q = new ArrayDeque<>();
  private int count = 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class DataStream:
  def __init__(self, value: int, k: int):
    self.value = value
    self.k = k
    self.q = deque()
    self.count = 0

  def consec(self, num: int) -> bool:
    if len(self.q) == self.k and self.q.popleft() == self.value:
      self.count -= 1
    if num == self.value:
      self.count += 1
    self.q.append(num)
    return self.count == self.k