January 18, 2025 |35.4K Views

Longest Subarray With Equal Number of 0s and 1s

Explore Courseexplore course icon
Description
Discussion

The task is to find the longest subarray in a binary array with an equal number of 0s and 1s. A naive approach involves using a nested loop to calculate the sum of subarrays while treating 0s as -1. If the cumulative sum of a subarray equals zero, the subarray has an equal number of 0s and 1s, and the length is updated. This approach has a time complexity of O(n^2), which is inefficient for larger arrays.

A more efficient approach uses a hash map and prefix sum technique, reducing time complexity to O(n). By treating 0s as -1, the problem is transformed into finding the longest subarray with a sum of 0. The hash map stores the first occurrence of each prefix sum. If a prefix sum repeats, it indicates a subarray with an equal number of 0s and 1s. The difference in indices gives the length of the subarray, and the maximum length is updated accordingly.

For more details, please go through - Longest Subarray With Equal Number of 0s and 1s