Skip to content

3028. Ant on the Boundary

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
class Solution {
 public:
  int returnToBoundaryCount(vector<int>& nums) {
    partial_sum(nums.begin(), nums.end(), nums.begin());
    return ranges::count(nums, 0);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int returnToBoundaryCount(int[] nums) {
    int ans = 0;
    int prefix = 0;

    for (final int num : nums) {
      prefix += num;
      if (prefix == 0)
        ++ans;
    }

    return ans;
  }
}
1
2
3
class Solution:
  def returnToBoundaryCount(self, nums: list[int]) -> int:
    return sum(prefix == 0 for prefix in itertools.accumulate(nums))