2 minute read

There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a string. No two pairs have the same id.

Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The concatenation of all the chunks should result in a list of the sorted values.

Implement the OrderedStream class:

OrderedStream(int n) Constructs the stream to take n values. String[] insert(int idKey, String value) Inserts the pair (idKey, value) into the stream, then returns the largest possible chunk of currently inserted values that appear next in the order.

/**
 * @param {number} n
 */
var OrderedStream = function (n) {
  // Get the 'n' to set array with 'n' length.
  this.array = new Array(n);
  // Initialize the pointer to indicate current position in the array.
  this.pointer = 0;
};

/**
 * @param {number} idKey
 * @param {string} value
 * @return {string[]}
 */
OrderedStream.prototype.insert = function (idKey, value) {
  // Assign value to index 'idKey' of the array.
  this.array[idKey - 1] = value;
  // Initialize the array to return result value.
  let result = [];

  // Loop through all element at the index of 'pointer'
  while (this.array[this.pointer]) {
    // Push the element at the index of 'pointer' in the array
    result.push(this.array[this.pointer]);
    // Increment the pointer
    this.pointer++;
  }
  // return result
  return result;
};

/**
 * Your OrderedStream object will be instantiated and called as such:
 * var obj = new OrderedStream(n)
 * var param_1 = obj.insert(idKey,value)
 */

In the constructor function, n is expected as a parameter, and an empty array is created with a length of n. The this.array is used to store values, and this.pointer is initialized to 0.

The insert method is used to insert a value along with its key. idKey is the key for the value, and value is the data to be inserted.

The idKey is assumed to be a 1-based index, so idKey - 1 is used to map it to the 0-based index in the array.

The value is stored in the array at the corresponding index.

The code then enters a loop where it checks if the value at the current pointer position (this.array[this.pointer]) is not null or undefined. If there is a value at the current position, it is pushed into the result array, and the pointer is incremented.

The loop continues until an empty slot is encountered in the array, and then it returns the result array, which contains all the values in sequential order starting from the current pointer position.

Leave a comment