LeetCode solutions

2878. Apply Operations to Make All Array Elements Equal to Zero

My accepted Python solution to LeetCode problem 2878, Apply Operations to Make All Array Elements Equal to Zero, running in 32ms.

  • Difficulty: Medium
  • Python
  • Runtime 32ms
  • Memory 30.2MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 32ms, memory 30.2MB, accepted 2026-01-01.

python
class Solution:
    def checkArray(self, nums: List[int], k: int) -> bool:
        n = len(nums)
        # diff[i] = how much we're currently subtracting at position i
        # due to operations that started before i
        diff = [0] * (n + 1)
        current = 0  # running sum of decrements
        
        for i in range(n):
            current += diff[i]
            effective = nums[i] - current
            
            if effective < 0:
                return False
            if effective > 0:
                # We need to start 'effective' operations at position i
                if i + k > n:
                    return False
                current += effective
                diff[i + k] -= effective
        
        return True

Source