Sliding Window Counting windows

182. Binary Subarrays With Sum

Medium 147 DSA Sheet

You are given an array nums in which every element is 0 or 1, and an integer k. Return the number of subarrays that hold exactly k ones. In other words, count the subarrays whose elements add up to k.

A subarray is a contiguous sequence of elements from nums, with at least one element. Two subarrays are different if they start or end at different positions.

Example 1

Input: nums = [1, 0, 1, 0, 0, 1], k = 2

Output: 5

Explanation: Five subarrays hold exactly two 1s: [1,0,1], [1,0,1,0] and [1,0,1,0,0], which start at index 0, and [0,1,0,0,1] and [1,0,0,1], which end at the last index.

Example 2

Input: nums = [0, 0, 1, 0], k = 0

Output: 4

Explanation: With k = 0 only the subarrays made of 0s count. The first two 0s give [0] twice and [0,0] once, and the last 0 gives one more [0].

Example 3

Input: nums = [0, 1, 0, 0], k = 2

Output: 0

Explanation: The array holds only one 1, so no subarray holds two.

Check your understanding

Work out the answer for this input before you write any code.

nums = [0, 0, 0, 0], k = 0

Constraints

  • 1 ≤ nums.length ≤ 105
  • nums[i] is 0 or 1
  • 0 ≤ k ≤ nums.length

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.