leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit 933b3b41aa8f2286e7f2f846925b45c8df15282d
parent 6c5db50fce3a14a2205e7d927c8adaf829aa6280
Author: Jack Sangdahl <jack@pngu.org>
Date:   Mon, 18 Aug 2025 21:36:14 -0600

2348. number of zero-filled subarrays

Diffstat:
Mnum_zero_filled_subarr.c | 18++++++++++--------
Anum_zero_filled_subarr.py | 29+++++++++++++++++++++++++++++
2 files changed, 39 insertions(+), 8 deletions(-)

diff --git a/num_zero_filled_subarr.c b/num_zero_filled_subarr.c @@ -1,17 +1,19 @@ // 2348. Number of Zero-Filled Subarrays -#include <stdio.h> +#include "leetcode.h" // given integer array 'nums', return number of subarrays filled with zero. a // subarray is a contiguous non-empty sequence of elements from within an array -long long zeroFilledSubarray(int *nums, int nums_size) { - long long ans = 0; - for (int i = 0, j = 0; i < nums_size; ++i) { - if (nums[i] != 0) - j = i + 1; - ans += i - j + 1; +long long zeroFilledSubarray(int *nums, int numsSize) { + long long cnt = 0, streak = 0; + for (int i = 0; i < numsSize; i++) { + if (!nums[i]) { + streak++; + cnt += streak; + } else + streak = 0; } - return ans; + return cnt; } int main() { diff --git a/num_zero_filled_subarr.py b/num_zero_filled_subarr.py @@ -0,0 +1,29 @@ +# 2348. Number of Zero-Filled Subarrays + +""" +given integer array 'nums', return number of subarrays filled with zero. a +subarray is a contiguous non-empty sequence of elements from within an array +""" + + +class Solution(object): + def zeroFilledSubarray(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + cnt, streak = 0 + for i in nums: + if i == 0: + streak += 1 + cnt += streak + else: + streak = 0 + return cnt + + +if __name__ == "__main__": + obj = Solution() + print(obj.zeroFilledSubarray(nums=[1, 3, 0, 0, 2, 0, 0, 4])) + print(obj.zeroFilledSubarray(nums=[0, 0, 0, 2, 0, 0])) + print(obj.zeroFilledSubarray(nums=[2, 10, 2019]))