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
Contiguous subarray with 0 and 1 in JavaScript
In JavaScript, finding the longest contiguous subarray with equal numbers of 0s and 1s in a binary array is a classic problem that can be solved efficiently using a hash map approach.
Problem Statement
Given a binary array containing only 0s and 1s, find the length of the longest contiguous subarray that contains an equal number of 0s and 1s.
For example, with the input array:
const arr = [1, 0, 0, 1, 0, 1, 0, 0];
console.log("Input array:", arr);
Input array: [1, 0, 0, 1, 0, 1, 0, 0]
The expected output is 6, because the first 6 elements [1, 0, 0, 1, 0, 1] contain three 1s and three 0s.
Algorithm Approach
The key insight is to transform 0s to -1s, so when we calculate a running sum, equal numbers of 0s and 1s will result in a sum of 0. We use a hash map to store the first occurrence of each sum value.
Solution Implementation
const arr = [1, 0, 0, 1, 0, 1, 0, 0];
const findMaxLength = (arr = []) => {
const { length } = arr;
// Edge case: less than 2 elements cannot have equal 0s and 1s
if (length < 2) {
return 0;
};
// Map to store first occurrence of each sum
const map = new Map();
map.set(0, -1); // Initialize with sum 0 at index -1
let sum = 0;
let max = 0;
for (let i = 0; i < length; i++) {
// Transform 0 to -1, keep 1 as 1
sum += arr[i] === 0 ? -1 : 1;
if (map.has(sum)) {
// If sum seen before, calculate subarray length
max = Math.max(max, i - map.get(sum));
} else {
// Store first occurrence of this sum
map.set(sum, i);
}
}
return max;
};
console.log("Input:", arr);
console.log("Length of longest equal subarray:", findMaxLength(arr));
Input: [1, 0, 0, 1, 0, 1, 0, 0] Length of longest equal subarray: 6
How It Works
The algorithm works by:
- Transformation: Convert each 0 to -1, keeping 1s unchanged
- Running Sum: Calculate cumulative sum as we traverse the array
- Hash Map: Store the first occurrence index of each sum value
- Length Calculation: When a sum repeats, the subarray between the two positions has equal 0s and 1s
Step-by-Step Example
const arr = [1, 0, 0, 1, 0, 1];
function findMaxLengthDetailed(arr) {
const map = new Map();
map.set(0, -1);
let sum = 0;
let max = 0;
console.log("Index | Value | Sum | Map State | Max Length");
console.log("------|-------|-----|-----------|----------");
for (let i = 0; i < arr.length; i++) {
sum += arr[i] === 0 ? -1 : 1;
if (map.has(sum)) {
const prevIndex = map.get(sum);
const length = i - prevIndex;
max = Math.max(max, length);
console.log(` ${i} | ${arr[i]} | ${sum} | ${JSON.stringify([...map])} | ${max}`);
} else {
map.set(sum, i);
console.log(` ${i} | ${arr[i]} | ${sum} | ${JSON.stringify([...map])} | ${max}`);
}
}
return max;
}
findMaxLengthDetailed(arr);
Index | Value | Sum | Map State | Max Length ------|-------|-----|-----------|---------- 0 | 1 | 1 | [[0,-1],[1,0]] | 0 1 | 0 | 0 | [[0,-1],[1,0]] | 2 2 | 0 | -1 | [[0,-1],[1,0],[-1,2]] | 2 3 | 1 | 0 | [[0,-1],[1,0],[-1,2]] | 4 4 | 0 | -1 | [[0,-1],[1,0],[-1,2]] | 4 5 | 1 | 0 | [[0,-1],[1,0],[-1,2]] | 6
Time and Space Complexity
- Time Complexity: O(n) - single pass through the array
- Space Complexity: O(n) - hash map can store at most n+1 entries
Conclusion
This approach efficiently finds the longest contiguous subarray with equal 0s and 1s by transforming the problem into finding repeated cumulative sums. The hash map optimization reduces the time complexity from O(n²) brute force to O(n).
