Contiguous Array
Contiguous Array is a medium arrays & hashing problem solved with the prefix sum strategy pattern.
The best approach, optimal (prefix balance + first-seen map), runs in O(n) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (every start, extend right) up.
Problem
You are given a binary array nums (every element is 0 or 1). Find the length of the longest contiguous subarray that contains the same number of 0s and 1s.
If no such subarray exists, return 0.
Examples
Example 1
- Input
nums = [1, 1, 0, 1, 0, 0, 1]- Output
6- Why
- The window [1, 0, 1, 0, 0, 1] (indices 1 to 6) has three 0s and three 1s; no window of length 7 is balanced because 7 is odd.
Example 2
- Input
nums = [0, 0, 0, 1]- Output
2- Why
- Only the last two elements [0, 1] are balanced.
Example 3
- Input
nums = [1, 1, 1]- Output
0- Why
- There is no 0 at all, so no balanced subarray exists.
Constraints
1 <= nums.length <= 10^5nums[i]is either0or1
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (every start, extend right) | O(n²) | O(1) |
| Optimal (prefix balance + first-seen map) | O(n) | O(n) |
1Brute force (every start, extend right)
O(n²)Every pair (i, j) is visited once.O(1)Only two counters.Fix a start index and grow the window to the right, keeping a running count of zeros and ones. Every time the two counts match, the window is balanced and its length is a candidate.
- For each start i, set zeros = ones = 0.
- For each end j >= i, increment zeros or ones for nums[j].
- If zeros == ones, update best with j - i + 1.
- Return best.
class Solution {
public int findMaxLength(int[] nums) {
int n = nums.length, best = 0;
for (int i = 0; i < n; i++) {
int zeros = 0, ones = 0;
for (int j = i; j < n; j++) {
if (nums[j] == 0) zeros++; else ones++;
if (zeros == ones) best = Math.max(best, j - i + 1);
}
}
return best;
}
}class Solution:
def findMaxLength(self, nums: List[int]) -> int:
n, best = len(nums), 0
for i in range(n):
zeros = ones = 0
for j in range(i, n):
if nums[j] == 0:
zeros += 1
else:
ones += 1
if zeros == ones:
best = max(best, j - i + 1)
return bestclass Solution {
public:
int findMaxLength(vector<int>& nums) {
int n = nums.size(), best = 0;
for (int i = 0; i < n; i++) {
int zeros = 0, ones = 0;
for (int j = i; j < n; j++) {
if (nums[j] == 0) zeros++; else ones++;
if (zeros == ones) best = max(best, j - i + 1);
}
}
return best;
}
};function findMaxLength(nums) {
const n = nums.length;
let best = 0;
for (let i = 0; i < n; i++) {
let zeros = 0, ones = 0;
for (let j = i; j < n; j++) {
if (nums[j] === 0) zeros++; else ones++;
if (zeros === ones) best = Math.max(best, j - i + 1);
}
}
return best;
}2Optimal (prefix balance + first-seen map)
O(n)One pass with O(1) map operations per element.O(n)The balance ranges over at most 2n + 1 values, each stored once.Walk the array keeping a balance: +1 for a 1 and -1 for a 0. If the balance at index j equals the balance at an earlier index i, the elements between them contain as many 0s as 1s. Store the first index at which each balance appears (balance 0 at index -1), so the window for a repeated balance is as long as possible.
- Create a map with balance 0 -> index -1.
- For each index j, add +1 for a 1 or -1 for a 0 to balance.
- If balance is already in the map, update best with j - map[balance].
- Otherwise store balance -> j (only the first occurrence is kept).
- Return best.
class Solution {
public int findMaxLength(int[] nums) {
Map<Integer, Integer> first = new HashMap<>();
first.put(0, -1);
int balance = 0, best = 0;
for (int j = 0; j < nums.length; j++) {
balance += nums[j] == 1 ? 1 : -1;
Integer i = first.get(balance);
if (i != null) best = Math.max(best, j - i);
else first.put(balance, j);
}
return best;
}
}class Solution:
def findMaxLength(self, nums: List[int]) -> int:
first = {0: -1}
balance = best = 0
for j, x in enumerate(nums):
balance += 1 if x == 1 else -1
if balance in first:
best = max(best, j - first[balance])
else:
first[balance] = j
return bestclass Solution {
public:
int findMaxLength(vector<int>& nums) {
unordered_map<int, int> first;
first[0] = -1;
int balance = 0, best = 0;
for (int j = 0; j < (int)nums.size(); j++) {
balance += nums[j] == 1 ? 1 : -1;
auto it = first.find(balance);
if (it != first.end()) best = max(best, j - it->second);
else first[balance] = j;
}
return best;
}
};function findMaxLength(nums) {
const first = new Map([[0, -1]]);
let balance = 0, best = 0;
for (let j = 0; j < nums.length; j++) {
balance += nums[j] === 1 ? 1 : -1;
if (first.has(balance)) best = Math.max(best, j - first.get(balance));
else first.set(balance, j);
}
return best;
}Edge cases to test
- All zeros or all ones: the answer is 0
- The whole array is balanced
- A single element
- The best window starts at index 0 (prefix balance returns to 0)
Hints
Hint 1
Replace every 0 with -1. A balanced subarray is then a subarray whose sum is 0.
Hint 2
A subarray i+1..j sums to 0 exactly when the prefix sums at i and j are equal.
Hint 3
Remember the first index where each prefix sum appeared; the longest window for that sum ends at the latest index.
FAQ
What is the best time complexity for Contiguous Array?
Optimal (prefix balance + first-seen map) runs in O(n) time and O(n) extra space. One pass with O(1) map operations per element.
Which pattern does Contiguous Array use?
It is a arrays & hashing problem that uses the prefix sum strategy pattern. Other problems with the same pattern: Subarray Sum Equals K, Subarray with given XOR, Range Sum Query - Immutable.
Is there a brute force solution for Contiguous Array?
Yes. Brute force (every start, extend right) takes O(n²) time and O(1) space. Fix a start index and grow the window to the right, keeping a running count of zeros and ones.
Which edge cases should I test for Contiguous Array?
All zeros or all ones: the answer is 0; The whole array is balanced; A single element; The best window starts at index 0 (prefix balance returns to 0).