Count 1's in a Sorted Binary Array

ZeeshanAli-0704 - Dec 3 '22 - - Dev Community

Below code is generic can be used to find occurrences of any number provided array is sorted with only 2 unique element

var getOneCount = function (nums, target) {
  let high = nums.length - 1;
  let low = 0;

  while (low <= high) {
    let mid = parseInt((low + high) / 2);

    if (nums[mid] > target) {
      high = mid - 1;
    } else if (nums[mid] < target) {
      low = mid + 1;
    } else {
      if (mid === 0 || nums[mid - 1] !== nums[mid]) {
        return nums.length - mid;
      } else {
        high = mid - 1;
      }
    }
  }

  return -1;
};

console.log(getOneCount([0, 0, 1, 1, 1, 1, 1], 1));

Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player