Count Nonempty Binary Segments with an Exact Sum

Quick Overview

Count Nonempty Binary Segments with an Exact Sum. Given binary array nums and goal, count the nonempty contiguous subarrays whose sum equals goal.

Count Nonempty Binary Segments with an Exact Sum

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem Given binary array `nums` and `goal`, count the nonempty contiguous subarrays whose sum equals goal. Return the number of index intervals, including distinct intervals with identical values. ```cpp class Solution { public: int numSubarraysWithSum(vector<int>& nums, int goal); }; ``` ### Examples **Example 1:** ```text Input: nums = [0,1,0], goal = 1 Output: 4 Explanation: Qualifying zero-based intervals are[1,1],[0,1],[1,2],and[0,2]. ``` **Example 2:** ```text Input: nums = [0,0,1], goal = 0 Output: 3 Explanation: The first two zeros contribute two singleton intervals and their combined interval. ``` ### Constraints - `1 <= nums.length <= 3*10^4`. - Each value is0 or1. - `0 <= goal <= nums.length`. ### Contract considerations Contiguous index intervals are required; arbitrary subsequences are not counted. ```hint Read the boundary condition Two prefix sums form a valid interval exactly when their difference is goal. ``` ### Boundary reminders Contiguous index intervals are required; arbitrary subsequences are not counted.

Overview: Count Nonempty Binary Segments with an Exact Sum. Given binary array nums and goal, count the nonempty contiguous subarrays whose sum equals goal.

Google logo
Google
Source window: 0–3 months · as of Oct 21, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Given binary array nums and goal, count the nonempty contiguous subarrays whose sum equals goal. Return the number of index intervals, including distinct intervals with identical values.

class Solution {
public:
    int numSubarraysWithSum(vector<int>& nums, int goal);
};

Examples

Example 1:

Input: nums = [0,1,0], goal = 1
Output: 4
Explanation: Qualifying zero-based intervals are[1,1],[0,1],[1,2],and[0,2].

Example 2:

Input: nums = [0,0,1], goal = 0
Output: 3
Explanation: The first two zeros contribute two singleton intervals and their combined interval.

Constraints

  • 1 <= nums.length <= 3*10^4 .
  • Each value is0 or1.
  • 0 <= goal <= nums.length .

Contract considerations

Contiguous index intervals are required; arbitrary subsequences are not counted.

Boundary reminders

Contiguous index intervals are required; arbitrary subsequences are not counted.