00:00

Problem Statement

Input/Output Examples

Visual Explanation

Seeding the map with prefix 0 counted once covers subarrays that start at index 0. Storing counts, not just presence, handles several earlier prefixes with the same value.

Approaches

The prefix-sum map is linear and works with negative numbers. The brute force tries every start.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of elements. The map version does one lookup and one update per element; the brute force considers all n(n + 1) / 2 subarrays.

Interview Tips and Recommended Approach

  • Seed prefix 0. Without it, subarrays starting at index 0 are missed.
  • Explain why a sliding window fails. Negative numbers mean the sum can shrink when the window grows.
  • Store counts, not booleans. Several prefixes can have the same value.
  • Know the variants: longest subarray with sum k, or sum divisible by k, use the same idea.

Recommended Approach: Prefix Sums in a HashMap

Why: it counts every matching subarray in one pass, works with negative values and is the core of a whole family of prefix-sum problems.