KatInterview

525. Contiguous Array

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the maximum length of a contiguous subarray within a binary array nums that has an equal number of 0s and 1s. A brute-force approach of checking every possible subarray would be too slow ($O(n^2)$ or $O(n^3)$), given the constraints ($n \le 10^5$). We need a more efficient method.

Solution

Contiguous Array in Python

class Solution:
    def findMaxLength(self, nums: List[int]) -> int:
        # Use a dictionary to store the first time a cumulative sum is seen.
        # Key: cumulative sum, Value: index
        count_map = {0: -1}
        # Initialize the map with a sum of 0 at index -1.
        # This handles cases where the subarray with sum 0 starts from index 0.
        
        max_length = 0
        count = 0  # Represents the cumulative sum

        for i, num in enumerate(nums):
            # Treat 0 as -1 and 1 as 1. Update the running count.
            if num == 1:
                count += 1
            else:
                count -= 1

            # If this count has been seen before...
            if count in count_map:
                # ...it means the subarray between the current index 'i'
                # and the previous index 'count_map[count]' has an equal number of 0s and 1s.
                # Calculate the length and update max_length.
                max_length = max(max_length, i - count_map[count])
            else:
                # If this is the first time we see this count, store the index.
                # We only store the first occurrence to maximize the length.
                count_map[count] = i

        return max_length

Contiguous Array in Java

class Solution {
    public int findMaxLength(int[] nums) {
        // Use a map to store the first time a cumulative sum is seen.
        // Key: cumulative sum, Value: index
        Map<Integer, Integer> map = new HashMap<>();
        // Initialize the map with a sum of 0 at index -1.
        // This handles cases where the subarray with sum 0 starts from index 0.
        map.put(0, -1);

        int maxLength = 0;
        int count = 0; // Represents the cumulative sum

        for (int i = 0; i < nums.length; i++) {
            // Treat 0 as -1 and 1 as 1. Update the running count.
            if (nums[i] == 1) {
                count++;
            } else {
                count--;
            }

            // If this count has been seen before...
            if (map.containsKey(count)) {
                // ...it means the subarray between the current index 'i'
                // and the previous index 'map.get(count)' has an equal number of 0s and 1s.
                // Calculate the length and update maxLength.
                maxLength = Math.max(maxLength, i - map.get(count));
            } else {
                // If this is the first time we see this count, store the index.
                // We only store the first occurrence to maximize the length.
                map.put(count, i);
            }
        }

        return maxLength;
    }
}

Contiguous Array in C++

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        // Use a map to store the first time a cumulative sum is seen.
        // Key: cumulative sum, Value: index
        unordered_map<int, int> map;
        // Initialize the map with a sum of 0 at index -1.
        // This handles cases where the subarray with sum 0 starts from index 0.
        map[0] = -1;

        int maxLength = 0;
        int count = 0; // Represents the cumulative sum

        for (int i = 0; i < nums.size(); ++i) {
            // Treat 0 as -1 and 1 as 1. Update the running count.
            if (nums[i] == 1) {
                count += 1;
            } else {
                count -= 1;
            }

            // If this count has been seen before...
            if (map.count(count)) {
                // ...it means the subarray between the current index 'i'
                // and the previous index 'map[count]' has an equal number of 0s and 1s.
                // Calculate the length and update maxLength.
                maxLength = max(maxLength, i - map[count]);
            } else {
                // If this is the first time we see this count, store the index.
                // We only store the first occurrence to maximize the length.
                map[count] = i;
            }
        }

        return maxLength;
    }
};

Contiguous Array in TypeScript

function findMaxLength(nums: number[]): number {
    // Use a map to store the first time a cumulative sum is seen.
    // Key: cumulative sum, Value: index
    const map = new Map<number, number>();
    // Initialize the map with a sum of 0 at index -1.
    // This handles cases where the subarray with sum 0 starts from index 0.
    map.set(0, -1);

    let maxLength = 0;
    let count = 0; // Represents the cumulative sum

    for (let i = 0; i < nums.length; i++) {
        // Treat 0 as -1 and 1 as 1. Update the running count.
        if (nums[i] === 1) {
            count++;
        } else {
            count--;
        }

        // If this count has been seen before...
        if (map.has(count)) {
            // ...it means the subarray between the current index 'i'
            // and the previous index 'map.get(count)' has an equal number of 0s and 1s.
            // Calculate the length and update maxLength.
            maxLength = Math.max(maxLength, i - map.get(count)!);
        } else {
            // If this is the first time we see this count, store the index.
            // We only store the first occurrence to maximize the length.
            map.set(count, i);
        }
    }

    return maxLength;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.