algoadvance

Leetcode 1656. Design an Ordered Stream

Problem Statement

You are given an OrderedStream class that consists of:

Initially, the pointer is set to 1. When you insert a pair, it should return an array containing the largest chunk of consecutive non-null values, starting from the current position of the pointer. Then move the pointer past these inserted values.

Example

Clarifying Questions

  1. Is the idKey guaranteed to be within the range 1 to n?
  2. Can we assume that the insertions will be valid, i.e., no duplicate keys or out-of-order issues needing special handling?
  3. Should the stream always maintain the order of inserted elements, or do we need to sort them before returning?

Strategy

  1. Initialize an array to store strings with a size of n and set a pointer to the first position.
  2. During insertion, place the value in its corresponding position in the array (account for 1-based index by subtracting 1).
  3. After insertion, check from the current pointer position for the longest consecutive non-null chunk.
  4. Accumulate this chunk, update the pointer, and return the accumulated values.

Code

Here is a C++ implementation of the OrderedStream class:

#include <vector>
#include <string>

class OrderedStream {
public:
    OrderedStream(int n) : stream(n), ptr(0) {}

    std::vector<std::string> insert(int idKey, const std::string& value) {
        stream[idKey - 1] = value;  // Insert the value at the 1-based index adjusted for 0-based array
        std::vector<std::string> result;

        // Collect all consecutive non-null values starting from the pointer
        while (ptr < stream.size() && !stream[ptr].empty()) {
            result.push_back(stream[ptr]);
            ++ptr;
        }

        return result;
    }

private:
    std::vector<std::string> stream;
    int ptr;
};

Time Complexity

This approach ensures efficient management of the stream while maintaining a clear and straightforward implementation.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI