Ant on the Boundary

An ant is on a boundary. It sometimes goes left and sometimes right.

You are given an array of non-zero integers nums. The ant starts reading nums from the first element to the end. At each step, it moves according to the value of the current element:

  • If nums[i] < 0, it moves left by -nums[i] units.
  • If nums[i] > 0, it moves right by nums[i] units.

Return the number of times the ant returns to the boundary.

Notes:

  • There is an infinite space on both sides of the boundary.
  • We check whether the ant is on the boundary only after it has moved |nums[i]| units. In other words, if the ant crosses the boundary during its movement, it does not count.
Example 1
Inputnums = [2,3,-5]
Output1
After the third step, the ant is on the boundary, so it returned to the boundary once.
Example 2
Inputnums = [3,2,-3,-4]
Output0
The ant is never on the boundary after completing any move, so the answer is 0.

Constraints

  • 1 <= nums.length <= 100
  • -10 <= nums[i] <= 10
  • nums[i] != 0

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate