Contiguous Array
Medium About 20 min Free, no account needed
Longest subarray holding as many zeros as ones.
The brief
Given a binary array nums (only 0s and 1s), return the length of the
longest contiguous subarray containing an equal number of 0s and 1s.
The obvious approach checks every starting index with an inner balance scan, O(n2), far too slow on the hidden 200,000-element test. You need a single pass that does not re-examine every starting index.
Starter code
using System;
public class Solution
{
// TODO: return the length of the longest contiguous subarray with equally many 0s and 1s.
public int FindMaxLength(int[] nums)
{
throw new NotImplementedException();
}
}How it is graded
Visible examples help you iterate. Hidden tests then cover edge cases and larger inputs, and every test reports server-measured time and allocated bytes.
What it practices
- Prefix sums
- Carry running totals or prefix state so any range question becomes a lookup.
- Hash maps and sets
- Trade memory for constant-time lookups, membership tests and frequency counts.
Related katas
- Subarray Sum Equals K Medium Free Count contiguous subarrays whose elements sum to a target k.
- Longest Well-Performing Interval Hard Free Longest stretch of days with more tiring days than easy ones.
- Degree of an Array Medium Free Find the shortest contiguous slice whose most-frequent-element count matches the whole array.
- Find All Anagram Start Indices Medium Free Every position where an anagram of the pattern begins.