Skip to main content
Back to problems
#3028
Easy Algorithms

Ant on the boundary

Array Simulation Prefix Sum
74.3% acceptance
Feb 25, 2026
170
53
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 of it to its 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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn return_to_boundary_count(nums: Vec<i32>) -> i32 {
    let mut pos = 0i32;
    nums.iter().filter(|&&x| { pos += x; pos == 0 }).count() as i32
  }
}