Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Practice] Get the count of Ones in a sorted array of 0s and 1s #23

Open
lpatmo opened this issue Jan 22, 2019 · 1 comment
Open

[Practice] Get the count of Ones in a sorted array of 0s and 1s #23

lpatmo opened this issue Jan 22, 2019 · 1 comment
Labels

Comments

@lpatmo
Copy link
Member

lpatmo commented Jan 22, 2019

Given a sorted array of 0s and 1s, count the number of ones in the array.

Requirement: Challenge: perform this in O(log(N)) time complexity.

console.log(findOnes([0,0,1,1,1,1,1,1,1])); //7
console.log(findOnes([0,1])); //1
console.log(findOnes([0,0,0,1,1,1,1,1,1,1,1]));  //8
console.log(findOnes([0,0,0]));  //0
console.log(findOnes([1,1,1,1,1,1]));  //6
console.log(findOnes([0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]));  //6
@lpatmo
Copy link
Member Author

lpatmo commented Jan 22, 2019

function findOnes(arr) {
  //choose an arbitrary midpoint (1/2 of array)
  //base case: midpoint = 1, and left number is 0
  //base case: last element is 0
  //base case: first element is 1
  //if midpoint is 0, move to right by arr up to midpoint divided by 2
  // if midpoint is 1, move to left by arr up to midpoint divided by 2... 
  let start = 0;
  let end = arr.length -1;
  let midpoint = Math.floor((start+end)/2);
 // console.log(midpoint)
  if (arr[midpoint] === 1 && arr[midpoint-1] === 0) {
    return arr.length - midpoint;
  }
  if (arr[arr.length-1] === 0) {
    return 0;
  }
  if (arr[0] === 1) {
    return arr.length;
  }
  //console.log('midpiont initial', midpoint)
  //Basically practicing binary search below: 
  while (start < end) {
    if (arr[midpoint] === 1 && arr[midpoint-1] === 0) {
       return arr.length - midpoint; //not happy with this, but it's a necessary check
    }
    if (arr[midpoint] === 0) {
      start = midpoint + 1;
    } else {
      end = midpoint - 1;
    }
    midpoint = Math.floor((start+end)/2);
  }
  return arr.length - midpoint;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant