525. Contiguous Array LeetCode Solution

In this guide, you will get 525. Contiguous Array LeetCode Solution with the best time and space complexity. The solution to Contiguous Array problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Contiguous Array solution in C++
  4. Contiguous Array solution in Java
  5. Contiguous Array solution in Python
  6. Additional Resources
525. Contiguous Array LeetCode Solution image

Problem Statement of Contiguous Array

Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.

Example 1:

Input: nums = [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.

Example 2:

Input: nums = [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.

Constraints:

1 <= nums.length <= 105
nums[i] is either 0 or 1.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

525. Contiguous Array LeetCode Solution in C++

class Solution {
 public:
  int findMaxLength(vector<int>& nums) {
    int ans = 0;
    int prefix = 0;
    unordered_map<int, int> prefixToIndex{{0, -1}};

    for (int i = 0; i < nums.size(); ++i) {
      prefix += nums[i] ? 1 : -1;
      if (const auto it = prefixToIndex.find(prefix);
          it != prefixToIndex.cend())
        ans = max(ans, i - it->second);
      else
        prefixToIndex[prefix] = i;
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

525. Contiguous Array LeetCode Solution in Java

class Solution {
  public int findMaxLength(int[] nums) {
    int ans = 0;
    int prefix = 0;
    Map<Integer, Integer> prefixToIndex = new HashMap<>();
    prefixToIndex.put(0, -1);

    for (int i = 0; i < nums.length; ++i) {
      prefix += nums[i] == 1 ? 1 : -1;
      if (prefixToIndex.containsKey(prefix))
        ans = Math.max(ans, i - prefixToIndex.get(prefix));
      else
        prefixToIndex.put(prefix, i);
    }

    return ans;
  }
}
// code provided by PROGIEZ

525. Contiguous Array LeetCode Solution in Python

class Solution:
  def findMaxLength(self, nums: list[int]) -> int:
    ans = 0
    prefix = 0
    prefixToIndex = {0: -1}

    for i, num in enumerate(nums):
      prefix += 1 if num else -1
      ans = max(ans, i - prefixToIndex.setdefault(prefix, i))

    return ans
# code by PROGIEZ

Additional Resources

See also  1991. Find the Middle Index in Array LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.