Problem 1658

Abstract / Summary

Given an integer x and an array of positive integers, find the least number of operations to reduce x to zero using the array values.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1658.py

class Solution:
    def minOperations(self, nums: List[int], x: int) -> int:
        if sum(nums) < x:
            return -1

        # greedy left side
        left = a = 0
        while a < x:
            a    += nums[left]
            left += 1

        best = left if a == x else float("inf")

        # right side
        right = b = 0
        while right < len(nums):
            right += 1
            b     += nums[-right]

            # fix overshooting
            while a + b > x and left > 0:
                left -= 1
                a    -= nums[left]

            if a + b == x:
                best = min(best, left + right)

        return best if best < float("inf") else -1
28 lines | 719 bytes | submitted September 20, 2023 | GitHub   15% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 41% (500k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Hash Table
  • Prefix Sum
  • Sliding Window
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The minOperations method determines the smallest number of elements that must be removed from either the beginning or the end of the integer list nums so that the sum of the removed elements equals the target value x. If no such combination exists, the method returns -1. The algorithm employs a two-pointer technique that expands a window from the left side, then incrementally incorporates elements from the right while shrinking the left side as needed to keep the combined sum from exceeding x.

Key Steps

Input validation

The first guard clause checks whether the total sum of the array is insufficient to reach x. When the overall sum is smaller, no sequence of removals can satisfy the requirement, and the function returns -1 immediately.

if sum(nums) < x:
    return -1

Expanding the left window

A greedy scan moves a left pointer forward, accumulating values in a until the partial sum reaches or exceeds x. The variables left and a track the number of elements taken from the left and their cumulative sum, respectively.

left = a = 0
while a < x:
    a    += nums[left]
    left += 1

Initial best candidate

If the left-side accumulation lands exactly on x, the current count of taken elements (left) becomes a candidate for the minimal operation count. Otherwise, the candidate is set to an infinite sentinel, indicating that a valid solution has not yet been found.

best = left if a == x else float("inf")

Expanding from the right and adjusting the left side

A second pointer iterates from the end of the list, adding elements to the right-side sum b. After each addition, the algorithm checks whether the combined sum a + b overshoots x. If it does, a nested loop retracts the left pointer one step at a time, subtracting the corresponding values from a until the total no longer exceeds x or the left pointer cannot move further. When the combined sum matches x, the total number of removed elements (left + right) is compared with the current best and the minimum is retained.

right = b = 0
while right < len(nums):
    right += 1
    b     += nums[-right]

    # fix overshooting
    while a + b > x and left > 0:
        left -= 1
        a    -= nums[left]

    if a + b == x:
        best = min(best, left + right)

Final result selection

After the right-side scan completes, the method returns the smallest operation count found. If no valid combination was recorded (the sentinel value remains), -1 is returned to signal impossibility.

return best if best < float("inf") else -1

Edge Cases Handled

The implementation explicitly handles the scenario where the total sum of nums is less than x, returning -1 without further processing. When the left-side greedy accumulation reaches x exactly, the algorithm records this as a valid solution before any right-side elements are considered. The inner loop that retracts the left pointer ensures that any overshoot caused by adding a right-side element is corrected, allowing the algorithm to recover from intermediate states where a + b temporarily exceeds x. The condition left > 0 prevents the left pointer from moving past the start of the list, thereby avoiding out-of-range accesses. Additionally, the outer loop iterates up to the full length of nums, guaranteeing that cases where the solution consists solely of right-side removals are examined.

Performance Optimizations

The core of the method is a sliding-window approach that maintains two pointers (left and right) and updates the sums a and b incrementally. By adding or subtracting a single element at each step, the algorithm avoids recomputing sums from scratch, achieving constant-time updates for each pointer movement. The inner adjustment loop only runs when an overshoot occurs, and each element can be removed from the left side at most once, ensuring that the total number of pointer adjustments is bounded by the length of the list. This disciplined movement of pointers eliminates redundant work and keeps the overall execution tight. The use of a sentinel float("inf") for the best candidate avoids extra conditional checks during the scan, allowing the min operation to be applied directly when a valid sum is encountered.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long row of numbered blocks sitting on the floor. There is a goal number that needs to be reached by picking up blocks from either the far left end or the far right end of the line.

The code starts by checking if all the blocks added together are even big enough to reach the goal number. If the total is too small, it is impossible to win, so it stops there.

Next, it walks along the blocks starting from the left side and picks them up one by one, adding their values together. It keeps doing this until the total is equal to or bigger than the goal. If the total accidentally becomes exactly the goal, it remembers how many blocks were picked up as a potential best way to win.

After that, it starts looking at the blocks from the right side of the line. It adds one block from the right side and checks the current total. If that total is more than the goal, it puts a block back on the left side to make room for the new block from the right. This keeps the total amount of blocks as close to the goal as possible.

Every time the total of the blocks from the left and the right exactly matches the goal, it compares how many blocks were taken to the previous best way. By the time it finishes looking at every block, it knows the smallest number of blocks needed to reach the goal. If no combination works, it lets everyone know that the goal could not be reached.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 6.00 | σ = 1.47

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JS
lkwq007 Python
MacJim C++
martianoff Scala
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
MacJim C++
martianoff Scala
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
YuriSpiridonov Python
31 links | 19 authors | 9 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

4 medium 1 hard
6 solutions   September 20, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality