Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Prefix Sum Medium frequency Solution Available Practice Mode

Contiguous Array LeetCode Solution

Tags: #Array #Hash Map #Prefix Sum

Approach Summary

Replace 0s with -1s. Find longest subarray with sum 0 using prefix sum + hash map. Same as finding two equal prefix sums.

Practice Mode

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Prefix Sum Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Prefix Sum pattern.

Framework: Prefix Sum • Interview Prep: Tested at FAANG • Explore all Prefix Sum problems & invariants →

How to Recognize This Pattern

  • Equal number of 0s and 1s in subarray

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)

Tags

Array Hash Map Prefix Sum

Frequently Asked Questions

What is the optimal time and space complexity for Contiguous Array?
The optimal solution for Contiguous Array achieves O(n) runtime complexity and requires O(n) auxiliary space. A single pass with O(1) map operations — O(n) time. The map stores up to n distinct running sums — O(n) space.
How do I identify that Contiguous Array requires the Prefix Sum pattern?
In technical interviews, look for key problem signals: Equal number of 0s and 1s in subarray. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Prefix Sum strategy.
What critical edge cases must be handled in Contiguous Array?
Essential edge cases to verify include: No balanced subarray — returns 0; Balanced subarray starting at index 0 — the {0: -1} seed handles it; All zeros or all ones — longest balanced run is 0; An odd-length array cannot have a balanced full run but can contain one. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Contiguous Array?
Contiguous Array is a Medium-difficulty question tagged with medium recurrence. It is actively asked in technical screening and onsite interview loops at Facebook.
Buy me a coffee
Daily Practice
0/0