Program to find minimum operations to reduce X to zero in Python

We have an array called nums and a value x. In one operation, we can delete either the leftmost or rightmost element from the array and subtract its value from x. We need to find the minimum number of operations to reduce x to exactly 0.

The key insight is to use prefix and suffix sums. We can precompute all possible left prefix sums, then iterate through right suffix sums to find the optimal combination.

Algorithm Steps

The approach involves these steps ?

  • Create a map of left prefix sums with their indices
  • For each possible right suffix sum, check if the complementary left sum exists
  • Calculate minimum operations needed for each valid combination
  • Return the minimum operations or -1 if impossible

Example

Let's trace through an example where nums = [4,2,9,1,4,2,3] and x = 9 ?

def solve(nums, x):
    n = len(nums)
    
    # Build left prefix sums map
    leftMap = dict()
    leftMap[0] = -1  # No elements taken from left
    left = 0
    for i in range(n):
        left += nums[i]
        if left not in leftMap:
            leftMap[left] = i
    
    # Try all combinations of right suffix sums
    right = 0
    ans = n + 1
    for i in range(n, -1, -1):
        if i < n:
            right += nums[i]
        
        # Find required left sum
        left_needed = x - right
        if left_needed in leftMap:
            operations = leftMap[left_needed] + 1 + n - i
            ans = min(ans, operations)
    
    return -1 if ans == n + 1 else ans

# Test the example
nums = [4, 2, 9, 1, 4, 2, 3]
x = 9
result = solve(nums, x)
print(f"Minimum operations: {result}")
Minimum operations: 3

How It Works

For the example nums = [4,2,9,1,4,2,3] and x = 9 ?

  1. Left prefix sums: {0: -1, 4: 0, 6: 1, 15: 2, ...}
  2. Right suffix approach: We try taking 0, 1, 2... elements from right
  3. Optimal solution: Take 1 element from left (4) and 2 elements from right (2+3=5), totaling 4+5=9
  4. Operations: 1 + 2 = 3 operations

Complete Implementation

def min_operations_to_reduce_x(nums, x):
    n = len(nums)
    
    # Edge case: single element
    if n == 1:
        return 1 if nums[0] == x else -1
    
    # Build prefix sums from left
    prefix_map = {0: -1}  # sum: last_index
    current_sum = 0
    
    for i in range(n):
        current_sum += nums[i]
        if current_sum not in prefix_map:
            prefix_map[current_sum] = i
    
    # Try all suffix combinations
    suffix_sum = 0
    min_ops = float('inf')
    
    for i in range(n, -1, -1):
        if i < n:
            suffix_sum += nums[i]
        
        prefix_needed = x - suffix_sum
        
        if prefix_needed in prefix_map:
            left_ops = prefix_map[prefix_needed] + 1
            right_ops = n - i
            
            # Ensure no overlap
            if left_ops + right_ops <= n:
                min_ops = min(min_ops, left_ops + right_ops)
    
    return min_ops if min_ops != float('inf') else -1

# Test cases
test_cases = [
    ([4, 2, 9, 1, 4, 2, 3], 9),
    ([1, 1, 4, 2, 3], 5),
    ([5, 6, 7, 8, 9], 4),
    ([1, 2, 3, 4], 10)
]

for nums, x in test_cases:
    result = min_operations_to_reduce_x(nums, x)
    print(f"nums = {nums}, x = {x} ? {result}")
nums = [4, 2, 9, 1, 4, 2, 3], x = 9 ? 3
nums = [1, 1, 4, 2, 3], x = 5 ? 2
nums = [5, 6, 7, 8, 9], x = 4 ? -1
nums = [1, 2, 3, 4], x = 10 ? 4

Time Complexity

The algorithm has O(n) time complexity where n is the array length. We iterate through the array twice ? once to build the prefix map and once to check suffix combinations.

Conclusion

This problem uses prefix sums and hash maps to efficiently find the minimum operations. The key insight is checking all combinations of left prefix and right suffix sums that add up to x.

Updated on: 2026-03-26T13:53:22+05:30

426 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements