So, I have an array containing only 0\'s and 1\'s. I have to find out the largest subarray containing equal number of 0\'s and 1\'s. One can be a naive approach have complex
JS implementation of the @templatetypedef algorithm with a modification of using a map to help find the max length
function findMaxLen(a) {
// secondary array, initialized with the first element as 0
let b = [0]
let sum = 0
// populate the secondary array and update the sum as per the algorithm
for (let i = 0; i < a.length; i++) {
b[i + 1] = a[i] == 0 ? sum - 1 : sum + 1
sum = b[i + 1]
}
// map of sum vs the first index of the secondary array with the sum value
let map = new Map()
let maxLen = 0
for (let i = 0; i < b.length; i++) {
if (map.has(b[i]))
maxLen = Math.max(maxLen, i - map.get(b[i]))
else
map.set(b[i], i)
}
return maxLen
}