LeetCode Solutions

525. Contiguous Array

Time: $O(n)$

Space: $O(n)$

			

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 (prefixToIndex.count(prefix))
        ans = max(ans, i - prefixToIndex[prefix]);
      else
        prefixToIndex[prefix] = i;
    }

    return ans;
  }
};
			

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;
  }
}
			

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
      if prefix in prefixToIndex:
        ans = max(ans, i - prefixToIndex[prefix])
      else:
        prefixToIndex[prefix] = i

    return ans