Problem:
We are required to write a JavaScript function that takes in a binary array, arr, (an array that only consists of 0 or 1). Our function should return the length of the contiguous subarray from the array that consists of the same number of 1 and 0.
For example, if the input to the function is −
const arr = [1, 0, 0, 1, 0, 1, 0, 0];
Then the output should be −
const output = 6;
Output Explanation
The first 6 elements of the array are 1, 0, 0, 1, 0, 1 (three 1s and three 0s)
Example
The code for this will be −
const arr = [1, 0, 0, 1, 0, 1, 0, 0]; const findMaxLength = (arr = []) => { const { length } = arr; if (length < 2){ return 0 }; const map = new Map(); map.set(0, -1); let sum = 0; let max = 0; for (var i = 0; i < length; i++) { sum += arr[i] === 0 ? -1 : 1; if (map.has(sum)) { max = Math.max(max, i - map.get(sum)); } else { map.set(sum, i); }; }; return max; }; console.log(findMaxLength(arr));
Code Explanation
Here, we thought of 0 as -1 and 1 as 1, and calculated the sum for different windows, when sum is 0, we knew that subarray must have the same number of 0 and 1.
Output
And the output in the console will be −
6