Minimum Operations to Reduce X to Zero

MediumSliding Windowsliding window

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an array of positive integers nums and an integer x. In one operation you remove either the leftmost or the rightmost element of nums and subtract its value from x. Return the minimum number of operations needed to bring x down to **exactly** 0, or -1 if it cannot be done.

Examples

Input: nums = [1,1,4,2,3], x = 5
Output: 2
Remove the last two elements: 3 + 2 = 5.
Input: nums = [5,6,7,8,9], x = 4
Output: -1
Every element is larger than 4.
Input: nums = [3,2,20,1,1,3], x = 10
Output: 5
Remove 3 and 2 from the left and 3, 1, 1 from the right.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^4
  • 1 <= x <= 10^9

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More sliding window problems