Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding maximum number of consecutive 1's in a binary array in JavaScript
We are required to write a JavaScript function that takes in a binary array (an array that consists of 0 or 1 only) as the only argument.
The function should find the length of that consecutive subarray of the array that consists of only 1 and return it.
For example −
If the input array is −
const arr = [1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1];
Then the output should be −
4
We will use the sliding window algorithm to capture the largest window (largest in size) that consists of only 1.
Using Sliding Window Approach
The sliding window technique maintains two pointers to track consecutive sequences of 1s:
const arr = [1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1];
const findMaxConsecutiveOnes = (arr = []) => {
let left = 0;
let right = 0;
let max = 0;
while (right < arr.length) {
if (arr[right] === 0) {
if (right - left > max) {
max = right - left;
}
right++;
left = right;
} else {
right++;
}
}
return right - left > max ? right - left : max;
};
console.log(findMaxConsecutiveOnes(arr));
4
Alternative Simple Approach
A more straightforward method using a single counter:
const findMaxConsecutiveOnesSimple = (arr) => {
let maxCount = 0;
let currentCount = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === 1) {
currentCount++;
maxCount = Math.max(maxCount, currentCount);
} else {
currentCount = 0;
}
}
return maxCount;
};
const testArray = [1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1];
console.log(findMaxConsecutiveOnesSimple(testArray));
4
How It Works
The algorithm works by:
- Maintaining a current count of consecutive 1s
- Updating the maximum count whenever a longer sequence is found
- Resetting the current count to 0 when encountering a 0
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Sliding Window | O(n) | O(1) | Moderate |
| Simple Counter | O(n) | O(1) | High |
Conclusion
Both approaches efficiently find the maximum consecutive 1s in O(n) time. The simple counter method is more readable and easier to understand for beginners.
