Apply Operations to Make All Array Elements Equal to Zero - Problem

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.

Return true if you can make all the array elements equal to 0, or false otherwise.

A subarray is a contiguous non-empty part of an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,3,4], k = 3
Output: true
💡 Note: Apply operation on [2,1,3] twice to get [0,0,1,4], then on [0,1,4] once to get [0,0,0,3], then on [0,0,3] three times to get [0,0,0,0]
Example 2 — Impossible Case
$ Input: nums = [1,3,1,1], k = 2
Output: false
💡 Note: Cannot make all elements zero because the last element cannot be part of any k-sized subarray when operations are constrained
Example 3 — Edge Case
$ Input: nums = [0,0,0], k = 1
Output: true
💡 Note: All elements are already zero, no operations needed

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 106
  • 1 ≤ k ≤ nums.length

Visualization

Tap to expand
Apply Operations to Make All Array Elements Equal to Zero INPUT Array nums: 2 i=0 1 i=1 3 i=2 4 i=3 k = 3 Window size k=3: subarray Decrease any k elements by 1 in each operation ALGORITHM STEPS 1 Use Difference Array Track cumulative operations 2 Iterate Left to Right Process each element once 3 Apply Operations Make current element zero 4 Check Validity No negative operations Processing Steps: i=0: ops=2, diff[3]-=2 i=1: ops=1, diff[4]-=1 i=2: cur=3-2=1, ops=1 i=3: cur=4-2-1=1, ops=1 All elements --> 0 [OK] FINAL RESULT Final Array State: 0 0 0 0 Output: true All elements reduced to zero successfully! Operations Applied: Window [0,1,2]: 2 times Window [1,2,3]: 1 time Key Insight: Use a difference array to track the cumulative effect of operations efficiently. At each position i, apply exactly nums[i] operations to make it zero. If at any point we need negative operations or the window extends beyond array bounds, return false. Time: O(n), Space: O(n). TutorialsPoint - Apply Operations to Make All Array Elements Equal to Zero | Optimal Solution
Asked in
Google 15 Microsoft 12
18.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen