AlgoMaster Logo

Contiguous Array

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

In the brute force approach, we check all possible subarrays to determine if they contain an equal number of 0s and 1s. This can be done by calculating the sum of elements within every possible subarray where each '0' is treated as -1 and '1' as 1. A subarray with a sum of zero has equal numbers of 0s and 1s.

Code:

2. Prefix Sum + HashMap

Intuition:

To improve efficiency, we can use a prefix sum approach combined with a hash map. The key observation is that if two indices have the same prefix sum, the subarray between them has an equal number of 0s and 1s. We maintain a running sum where we treat 0 as -1 and 1 as 1. The hash map stores the first occurrence of each running sum. If at some index the running sum is the same as at a previous index, the subarray between those indices is balanced.

Code: