Skip to main content
Back to problems
Leetcode
Medium
Arrays
Simulation
Math
Ant On The Boundary

Simulate an ant walking on a number line and count how many times it returns to the origin.

Acceptance 0%
Problem Statement

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 the i-th move.

Output Format

  • Return a single integer: the number of times the running position becomes 0 after 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.
Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.