LeetCode 2526: Find Consecutive Integers from a Data Stream

Problem Description

Explanation

To solve this problem, we can use a deque data structure to keep track of the last k integers parsed in the stream. We will also maintain a count of the occurrences of the value in the current window of size k. Whenever a new integer is parsed, we add it to the deque and update the count of occurrences accordingly.

  1. Initialize the deque and count of occurrences.
  2. When a new integer is parsed, add it to the deque.
  3. If the deque size exceeds k, remove the oldest integer and update the count of occurrences.
  4. Check if the count of occurrences is equal to k. If yes, return true, else return false.

Time complexity: O(1) for each consec operation
Space complexity: O(k) for deque and count

Solutions

import java.util.*;

class DataStream {
    int value;
    int k;
    Deque<Integer> window;
    int count;

    public DataStream(int value, int k) {
        this.value = value;
        this.k = k;
        this.window = new ArrayDeque<>();
        this.count = 0;
    }

    public boolean consec(int num) {
        window.addLast(num);
        if (num == value) {
            count++;
        }
        if (window.size() > k) {
            int oldest = window.pollFirst();
            if (oldest == value) {
                count--;
            }
        }
        return count == k;
    }
}

Loading editor...