Javascript Program to Count 1's in a sorted binary array Last Updated : 16 Sep, 2024 Summarize Comments Improve Suggest changes Share Like Article Like Report Given a binary array sorted in non-increasing order, count the number of 1's in it. Examples: Input: arr[] = {1, 1, 0, 0, 0, 0, 0} Output: 2 Input: arr[] = {1, 1, 1, 1, 1, 1, 1} Output: 7 Input: arr[] = {0, 0, 0, 0, 0, 0, 0} Output: 0A simple solution is to traverse the array linearly. The time complexity of the simple solution is O(n). We can use Binary Search to find count in O(Logn) time. The idea is to look for the last occurrence of 1 using Binary Search. Once we find the index last occurrence, we return index + 1 as count.The following is the implementation of the above idea. JavaScript // Javascript program to count one's in a boolean array /* Returns counts of 1's in arr[low..high]. The array is assumed to be sorted in non-increasing order */ function countOnes(arr, low, high) { if (high >= low) { // get the middle index let mid = Math.trunc(low + (high - low) / 2); // check if the element at middle index is last 1 if ((mid == high || arr[mid + 1] == 0) && (arr[mid] == 1)) return mid + 1; // If element is not last 1, recur for right side if (arr[mid] == 1) return countOnes(arr, (mid + 1), high); // else recur for left side return countOnes(arr, low, (mid - 1)); } return 0; } // Driver program let arr = [1, 1, 1, 1, 0, 0, 0]; let n = arr.length; console.log("Count of 1's in given array is " + countOnes(arr, 0, n - 1)); OutputCount of 1's in given array is 4 Complexity Analysis:Time complexity: O(Logn).Space complexity: o(log n) (function call stack)The same approach with iterative solution would be JavaScript /* Returns counts of 1's in arr[low..high]. The array is assumed to be sorted in non-increasing order */ function countOnes(arr, n) { let ans; let low = 0, high = n - 1; while (low <= high) { // get the middle index let mid = Math.floor((low + high) / 2); // else recur for left side if (arr[mid] < 1) high = mid - 1; // If element is not last 1, recur for right side else if (arr[mid] > 1) low = mid + 1; else // check if the element at middle index is last 1 { if (mid == n - 1 || arr[mid + 1] != 1) return mid + 1; else low = mid + 1; } } } let arr = [1, 1, 1, 1, 0, 0, 0]; let n = arr.length; console.log("Count of 1's in given array is " + countOnes(arr, n)); // This code is contributed by unknown2108 OutputCount of 1's in given array is 4 Complexity Analysis:Time complexity: O(Logn)Space complexity: O(1) Please refer complete article on Count 1's in a sorted binary array for more details! Comment More infoAdvertise with us K kartik Follow Improve Article Tags : JavaScript Binary Search binary-string Practice Tags : Binary Search Similar Reads Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav 11 min read JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q 15+ min read Introduction to JavaScript JavaScript is a versatile, dynamically typed programming language used for interactive web applications, supporting both client-side and server-side development, and integrating seamlessly with HTML, CSS, and a rich standard library.JavaScript is a single-threaded language that executes one task at 7 min read JSON Web Token (JWT) A JSON Web Token (JWT) is a standard used to securely transmit information between a client (like a frontend application) and a server (the backend). It is commonly used to verify users' identities, authenticate them, and ensure safe communication between the two. JWTs are mainly used in web apps an 7 min read Frontend Developer Interview Questions and Answers Frontend development is an important part of web applications, and it is used to build dynamic and user-friendly web applications with an interactive user interface (UI). Many companies are hiring skilled Frontend developers with expertise in HTML, CSS, JavaScript, and modern frameworks and librarie 15+ min read JavaScript Coding Questions and Answers JavaScript is the most commonly used interpreted, and scripted Programming language. It is used to make web pages, mobile applications, web servers, and other platforms. Developed in 1995 by Brendan Eich. Developers should have a solid command over this because many job roles need proficiency in Jav 15+ min read Top 95+ Javascript Projects For 2025 JavaScript is a lightweight, cross-platform programming language that powers dynamic and interactive web content. From real-time updates to interactive maps and animations, JavaScript brings web pages to life.Here, we provided 95+ JavaScript projects with source code and ideas to provide hands-on ex 4 min read Functions in JavaScript Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs.JavaScriptfunction sum(x, y) { return x + y; } console.log(sum(6, 9)); // output: 15Function Syntax 5 min read JavaScript Exercises, Practice Questions and Solutions JavaScript Exercise covers interactive quizzes, tracks progress, and enhances coding skills with our engaging portal. Ideal for beginners and experienced developers, Level up your JavaScript proficiency at your own pace. Start coding now! A step-by-step JavaScript practice guide for beginner to adva 3 min read Like