Queue using List II

Another problem where you can implement a queue-like structure using a simple LinkedList. In this example, we keep track of the last K elements in a queue-implemented-as-linkedList, and a count of the instances of value. Code is down below, cheers, ACC.

Find Consecutive Integers from a Data Stream - LeetCode

2526. Find Consecutive Integers from a Data Stream
Medium

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.

 

Example 1:

Input
["DataStream", "consec", "consec", "consec", "consec"]
[[4, 3], [4], [4], [4], [3]]
Output
[null, false, false, true, false]

Explanation
DataStream dataStream = new DataStream(4, 3); //value = 4, k = 3 
dataStream.consec(4); // Only 1 integer is parsed, so returns False. 
dataStream.consec(4); // Only 2 integers are parsed.
                      // Since 2 is less than k, returns False. 
dataStream.consec(4); // The 3 integers parsed are all equal to value, so returns True. 
dataStream.consec(3); // The last k integers parsed in the stream are [4,4,3].
                      // Since 3 is not equal to value, it returns False.

 

Constraints:

  • 1 <= value, num <= 109
  • 1 <= k <= 105
  • At most 105 calls will be made to consec.
Accepted
9,191
Submissions
23,895

public class DataStream
{
    private LinkedList lastK = null;
    private int countValue = 0;
    private int k = 0;
    private int value = 0;
    public DataStream(int value, int k)
    {
        lastK = new LinkedList();
        countValue = 0;
        this.k = k;
        this.value = value;
    }

    public bool Consec(int num)
    {
        if (lastK.Count < k)
        {
            lastK.AddLast(num);
            if (num == value) countValue++;
            if (lastK.Count == k) return countValue == k;
            else return false;
        }
        else
        {
            if (lastK.First.Value == value) countValue--;
            lastK.RemoveFirst();

            lastK.AddLast(num);
            if (num == value) countValue++;
            return countValue == k;
        }
    }
}

Comments

Popular posts from this blog

Changing the root of a binary tree

ProjectEuler Problem 719 (some hints, but no spoilers)

The Power Sum, a recursive problem by HackerRank