LeetCode 1656: Design an Ordered Stream

Problem Description

Explanation:

  • We can use an array to store the values inserted in the stream.
  • We keep track of the last inserted id so that when a new pair is inserted, we can identify the largest chunk of currently inserted values that appear next in the order.
  • We return this chunk after each insertion.

Algorithm:

  1. Initialize an array stream of size n to store the values.
  2. Initialize a variable ptr to keep track of the last inserted id.
  3. In the insert function: a. Update the value at index idKey - 1 in stream. b. Check from ptr to n in the stream array to find the largest chunk of values that can be returned. c. Update ptr to idKey if the value at index ptr is not null. d. Return the chunk of values found.

Time Complexity: O(n) for each insert operation where n is the size of the stream.

Space Complexity: O(n) to store the stream of values.

:

Solutions

class OrderedStream {
    String[] stream;
    int ptr;

    public OrderedStream(int n) {
        stream = new String[n];
        ptr = 0;
    }

    public List<String> insert(int idKey, String value) {
        List<String> result = new ArrayList<>();

        stream[idKey - 1] = value;

        while (ptr < stream.length && stream[ptr] != null) {
            result.add(stream[ptr]);
            ptr++;
        }

        return result;
    }
}

Loading editor...