Categories
interview

Items in Container

// Items in container (Javascript)

var getItems = (str, startIndices, endIndices) => {
  var count = 0;
  var arr = Array(str.length);
  arr[0] = 0;
  for (let i = 1; i < str.length; i++) {
    var char = str.charAt(i);
    if (char === '*') {
      count++;
      arr[i] = arr[i - 1];
    } else {
      arr[i] = count;
    }
  }
  var ret = Array(startIndices.length);
  for (let i = 0; i < startIndices.length; i++) {
    var start = startIndices[i];
    var end = endIndices[i];
    ret[i] = arr[end - 1] - arr[start - 1];
  }
  return ret;
}

console.log(getItems('|**|*|*', [1, 1], [5, 6])); // [2,3]

Demo