Skip to content

525. Contiguous Array 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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
Back to top