Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2772: Apply Operations to Make All Array Elements Equal to Zero

In this guide, we solve Leetcode #2772 Apply Operations to Make All Array Elements Equal to Zero in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given a 0-indexed integer array nums and a positive integer k. You can apply the following operation on the array any number of times: Choose any subarray of size k from the array and decrease all its elements by 1.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Array, Prefix Sum

Intuition

Each operation decreases a length-k window by 1, so we only need to know how much total decrement is currently affecting index i.

If we track that running decrement with a difference array, we can greedily decide how many operations must start at i to make nums[i] become zero.

Approach

Maintain a difference array d and a running sum s of active decrements.

At each index, compute the effective value x = nums[i] + s. If x is negative, it is impossible. If x is positive, we must start x operations at i, which decreases s by x and ends those operations at i + k.

Steps:

  • Initialize a difference array d and running sum s.
  • For each index i, update s and compute the effective value.
  • If the value is positive, apply that many operations starting at i; if invalid, return False.

Example

Input: nums = [2,2,3,1,1,0], k = 3 Output: true Explanation: We can do the following operations: - Choose the subarray [2,2,3]. The resulting array will be nums = [1,1,2,1,1,0]. - Choose the subarray [2,1,1]. The resulting array will be nums = [1,1,1,0,0,0]. - Choose the subarray [1,1,1]. The resulting array will be nums = [0,0,0,0,0,0].

Python Solution

class Solution: def checkArray(self, nums: List[int], k: int) -> bool: n = len(nums) d = [0] * (n + 1) s = 0 for i, x in enumerate(nums): s += d[i] x += s if x == 0: continue if x < 0 or i + k > n: return False s -= x d[i + k] += x return True

Complexity

The time complexity is O(n)O(n)O(n), and the space complexity is O(n)O(n)O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy