LeetCode solutions

3643. Zero Array Transformation II

My accepted Python solution to LeetCode problem 3643, Zero Array Transformation II, running in 507ms.

  • Difficulty: Medium
  • Python
  • Runtime 507ms
  • Memory 63.9MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 507ms, memory 63.9MB, accepted 2025-12-31.

python
class Solution:
    def minZeroArray(self, nums: List[int], queries: List[List[int]]) -> int:
        n = len(nums)
        m = len(queries)
        
        def can_zero(k):
            # Check if first k queries can make all elements 0
            diff = [0] * (n + 1)
            for i in range(k):
                l, r, val = queries[i]
                diff[l] += val
                diff[r + 1] -= val
            
            coverage = 0
            for i in range(n):
                coverage += diff[i]
                if coverage < nums[i]:
                    return False
            return True
        
        # Check if even all queries can't make it zero
        if not can_zero(m):
            return -1
        
        # Check if already zero
        if all(x == 0 for x in nums):
            return 0
        
        # Binary search for minimum k
        lo, hi = 1, m
        while lo < hi:
            mid = (lo + hi) // 2
            if can_zero(mid):
                hi = mid
            else:
                lo = mid + 1
        
        return lo

Source