Binary Subarrays With Sum

Sliding Window / 2 Pointer Counting Subarrays / Substrings Problems Hard

Given a binary array nums and an integer goal. Return the number of non-empty subarrays with a sum goal.


A subarray is a continuous part of the array.

Constraints

  • 1 <= nums.length <= 3*104
  • 0 <= goal <= nums.length
  • nums consist of only 0 and 1.

Hints

  • Use a prefix sum to keep track of the cumulative sum up to each index. Store the count of each prefix sum in a hash map to efficiently determine how many subarrays with a sum equal to the goal exist.
  • For a subarray sum to equal the goal, the relationship current_sum−goal=prefix_sum must hold. Use the hash map to check how many times prefix_sum has occurred so far. Add that count to the result.

Company Tags

Stripe Nutanix Lyft Chewy Red Hat Roblox OYO Rooms Flipkart Siemens Healthineers Cerner Splunk Morgan Stanley Shopify Robinhood ARM Bain & Company Zoho AMD Deloitte McKinsey & Company HCL Technologies Databricks Target JPMorgan Chase Epic Games Google Microsoft Amazon Meta Apple Netflix Adobe