Simulate an ant walking on a number line and count how many times it returns to the origin.
Ant on the Boundary
An ant starts at position 0 on a one-dimensional number line. You are given a list of integers representing the ant's moves. For each move, the ant shifts left or right by the specified amount.
After every move, check whether the ant is exactly on the boundary, which in this problem means position 0.
Return the number of times the ant is at the boundary after completing a move.
Task
Compute how many prefixes of the move sequence have sum 0.
Notes
- The ant starts at position
0. - A positive value moves the ant to the right.
- A negative value moves the ant to the left.
- Count only positions reached after a move is applied.
Input Format
- An integer array
moves. - Each element
moves[i]is the signed displacement for thei-th move.
Output Format
- Return a single integer: the number of times the running position becomes
0after a move.
Constraints
1 <= moves.length- The move values are integers.
- Use a running sum to track the ant's position.
- The answer fits in a standard 32-bit signed integer.
Example 1
Input
moves = [2, -2, 3, -3, 1]
Output
2
Explanation
The running positions are 2, 0, 3, 0, 1. The ant is on the boundary twice.
Example 2
Input
moves = [1, 2, 3]
Output
0
Explanation
The running positions are 1, 3, 6. The ant never returns to 0.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.