Design an Ordered Stream

easy design array hash map

Problem

You receive a stream of n string values, each tagged with a unique id from 1 to n, but the ids may arrive in any order. Build a class with one method insert(idKey, value) that stores the value at its id and then returns the longest run of values whose ids are consecutive and start at the smallest id not yet returned. If the id you just inserted is not the next one expected, return an empty list — those values wait until the gap is filled.

Inputn = 5; insert(3,"ccccc"), insert(1,"aaaaa"), insert(2,"bbbbb"), insert(5,"eeeee"), insert(4,"ddddd")
Output[], ["aaaaa"], ["bbbbb","ccccc"], [], ["ddddd","eeeee"]
A pointer waits at id 1. Inserting 3 returns nothing (1 is still missing). Inserting 1 returns ["aaaaa"] and the pointer moves to 2. Inserting 2 sweeps up the already-present 3, so it returns ["bbbbb","ccccc"] and the pointer reaches 4. Inserting 5 returns nothing; inserting 4 finally releases both 4 and 5.

class OrderedStream:
    def __init__(self, n):
        self.vals = [None] * (n + 1)
        self.ptr = 1
    def insert(self, idKey, value):
        self.vals[idKey] = value
        chunk = []
        while self.ptr < len(self.vals) and self.vals[self.ptr] is not None:
            chunk.append(self.vals[self.ptr])
            self.ptr += 1
        return chunk
class OrderedStream {
  constructor(n) {
    this.vals = new Array(n + 1).fill(null);
    this.ptr = 1;
  }
  insert(idKey, value) {
    this.vals[idKey] = value;
    const chunk = [];
    while (this.ptr < this.vals.length && this.vals[this.ptr] !== null) {
      chunk.push(this.vals[this.ptr]);
      this.ptr++;
    }
    return chunk;
  }
}
class OrderedStream {
    String[] vals;
    int ptr;
    public OrderedStream(int n) {
        vals = new String[n + 1];
        ptr = 1;
    }
    public List<String> insert(int idKey, String value) {
        vals[idKey] = value;
        List<String> chunk = new ArrayList<>();
        while (ptr < vals.length && vals[ptr] != null) {
            chunk.add(vals[ptr]);
            ptr++;
        }
        return chunk;
    }
}
class OrderedStream {
    vector<string> vals;
    int ptr;
public:
    OrderedStream(int n) : vals(n + 1, ""), ptr(1) {}
    vector<string> insert(int idKey, string value) {
        vals[idKey] = value;
        vector<string> chunk;
        while (ptr < (int)vals.size() && !vals[ptr].empty()) {
            chunk.push_back(vals[ptr]);
            ptr++;
        }
        return chunk;
    }
};
Time: O(1) amortized per insert (O(n) total) Space: O(n)