Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Binary Subarrays With Sum

Count the number of contiguous subarrays whose elements sum to a given target.

Acceptance 93%
Problem Statement

Given a binary array and an integer goal, count how many contiguous subarrays have sum exactly equal to the goal.

A subarray must be non-empty and consist of consecutive elements from the array. Because the array contains only 0s and 1s, efficient counting techniques are often more useful than checking every subarray directly.

Input Format

  • An integer array nums containing only 0 and 1
  • An integer goal

The exact input encoding depends on the platform.

Output Format

Return the number of contiguous subarrays whose sum is exactly goal.

Constraints

  • 1 <= nums.length is assumed to be moderate to large
  • nums[i] is either 0 or 1
  • goal is a non-negative integer

Use the platform's official limits if available.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.