Advertisement
satishfrontenddev5

Untitled

Jan 6th, 2024
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. 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
  3.  
  4. Input format
  5. There are 2 lines of input
  6.  
  7. First line will contain a single integer n.
  8.  
  9. Next line will contain n space separated integers.
  10.  
  11. Output format
  12. Print the index of first occuring if present, otherwise print -1.
  13.  
  14. Sample Input 1
  15. 4
  16.  
  17. 0 0 1 1
  18.  
  19. Sample Output 1
  20. 2
  21.  
  22. Constraints
  23. 1<=n<=100000
  24.  
  25. 0<=Ai<=1
  26. */
  27.  
  28. function getRequiredIndex(n,arr){
  29.   let low = 0;
  30.   let high = n - 1;
  31.   while (low <= high) {
  32.     let mid = Math.floor((low + high) / 2);
  33.     if(arr[mid]==1)
  34.     return mid;
  35.     else if(1>arr[mid])
  36.      low=mid+1;
  37.      else
  38.      high=mid-1;
  39.   }
  40.   return -1;
  41. }
  42.  
  43. /**
  44.  * @param {number} n
  45.  * @param {number[]} arr
  46.  * @return {number}
  47.  */
  48. function zeroOnes(n, arr) {
  49.   let indexOfOne = getRequiredIndex(n, arr);
  50.   /* console.log(indexOfOne) */
  51.   if (indexOfOne == -1) return indexOfOne;
  52.   while (indexOfOne >= 0 && arr[indexOfOne] === 1) indexOfOne--;
  53.   return indexOfOne + 1;
  54. }
  55.  
  56. function main() {
  57.     let n = parseInt(readLine());
  58.     let arr = readIntArr();
  59.  
  60.     let firstIndex = zeroOnes(n, arr);
  61.     print(firstIndex);
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement