Minimum Operations to Reduce X to Zero Problem
Description
LeetCode Problem 1658.
You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.
Return the minimum number of operations to reduce x to exactly 0 if it is possible*, otherwise, return* -1.
Example 1:
Input: nums = [1,1,4,2,3], x = 5
Output: 2
Explanation: The optimal solution is to remove the last two elements to reduce x to zero.
Example 2:
Input: nums = [5,6,7,8,9], x = 4
Output: -1
Example 3:
Input: nums = [3,2,20,1,1,3], x = 10
Output: 5
Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^41 <= x <= 10^9
Solution
Approach: Hash Table + Prefix Sum
Removing elements from both ends leaves a contiguous middle part. Using the fewest operations means keeping the longest subarray whose sum is s = sum(nums) - x.
Scan the array with a running prefix sum t, and store in a hash table vis the first index where each prefix sum appears (with vis[0] = -1). At index i, if t - s is in vis, then the subarray from vis[t - s] + 1 to i sums to s, with length i - vis[t - s]. Keep the longest such length mx.
If no such subarray exists, return -1; otherwise return n - mx.
Complexity: O(n) time and O(n) space, where n is the length of nums.
class Solution:
def minOperations(self, nums: List[int], x: int) -> int:
s = sum(nums) - x
vis = {0: -1}
mx, t = -1, 0
for i, v in enumerate(nums):
t += v
if t not in vis:
vis[t] = i
if t - s in vis:
mx = max(mx, i - vis[t - s])
return -1 if mx == -1 else len(nums) - mx