Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Given a sorted array consisting of 0s and 1s only, find the index of the first 1. If there’s no 1 present in the array, return -1
- Input format
- There are 2 lines of input
- First line will contain a single integer n.
- Next line will contain n space separated integers.
- Output format
- Print the index of first occuring if present, otherwise print -1.
- Sample Input 1
- 4
- 0 0 1 1
- Sample Output 1
- 2
- Constraints
- 1<=n<=100000
- 0<=Ai<=1
- */
- function getRequiredIndex(n,arr){
- let low = 0;
- let high = n - 1;
- while (low <= high) {
- let mid = Math.floor((low + high) / 2);
- if(arr[mid]==1)
- return mid;
- else if(1>arr[mid])
- low=mid+1;
- else
- high=mid-1;
- }
- return -1;
- }
- /**
- * @param {number} n
- * @param {number[]} arr
- * @return {number}
- */
- function zeroOnes(n, arr) {
- let indexOfOne = getRequiredIndex(n, arr);
- /* console.log(indexOfOne) */
- if (indexOfOne == -1) return indexOfOne;
- while (indexOfOne >= 0 && arr[indexOfOne] === 1) indexOfOne--;
- return indexOfOne + 1;
- }
- function main() {
- let n = parseInt(readLine());
- let arr = readIntArr();
- let firstIndex = zeroOnes(n, arr);
- print(firstIndex);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement