Algorithm/NeetCode

Number of Zero-Filled Subarrays

Tony Lim 2024. 11. 13. 09:56
728x90

https://leetcode.com/problems/number-of-zero-filled-subarrays/description/

class Solution:
    def zeroFilledSubarray(self, nums: List[int]) -> int:
        i, res = 0, 0
        while i < len(nums):
            count = 0
            while i < len(nums) and nums[i] == 0:
                count += 1
                i += 1
                res += count
            i += 1

        return res


    def zeroFilledSubarray2(self, nums: List[int]) -> int:
        res, count = 0 ,0
        for i in range(len(nums)):
            if nums[i] == 0:
                count += 1
            else:
                count = 0
            res += count
        return res

point is as continous 0 subarray increase it has pattern

e.g) 0 => 1
00 => 1 + 2
000 => 1 + 2 + 3

because every time we add another zero it create itself as subarray of 0 and then create another subarray until total length of subarray

we can do that in while loop and for loop

728x90

'Algorithm > NeetCode' 카테고리의 다른 글

Design Underground System  (0) 2024.11.15
Optimal Partition of String  (0) 2024.11.14
First Missing Positive  (1) 2024.11.12
Non-decreasing Array  (2) 2024.11.11
Range Sum Query 2D - Immutable  (0) 2024.11.10