Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created August 19, 2025 20:30
Show Gist options
  • Save tatsuyax25/375e0cfb2acdc7a14a8908710f84b9ac to your computer and use it in GitHub Desktop.
Save tatsuyax25/375e0cfb2acdc7a14a8908710f84b9ac to your computer and use it in GitHub Desktop.
Given an integer array nums, return the number of subarrays filled with 0. A subarray is a contiguous non-empty sequence of elements within an array.
/**
* @param {number[]} nums
* @return {number}
*/
var zeroFilledSubarray = function(nums) {
let total = 0; // Final count of zero-filled subarrays
let count = 0; // Tracks length of current zero streak
for (let i = 0; i < nums.length; i++) {
if (nums[i] === 0) {
// Extend the current zero streak
count++;
} else if (count > 0) {
// End of a zero streak: add subarray count using arithmetic sum formula
total += (count * (count + 1)) / 2;
count = 0; // Reset for next streak
}
// If nums[i] !== 0 and count === 0, just continue
}
// Handle case where array ends with zeros
if (count > 0) {
total += (count * (count + 1)) / 2;
}
return total;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment