LeetCode 3028: Ant on the Boundary (Prefix Sum Counting)
LeetCode 3028SimulationPrefix SumToday we solve LeetCode 3028 - Ant on the Boundary.
Source: https://leetcode.com/problems/ant-on-the-boundary/
English
Problem Summary
You are given an integer array nums. Starting from position 0, an ant moves by each value in order. Count how many times the ant is exactly at position 0 after a move.
Key Insight
This is exactly a prefix-sum question. Let pos be the running sum of processed moves. Every time pos == 0, we found one return to the boundary.
Algorithm
- Initialize pos = 0, ans = 0.
- For each x in nums, do pos += x.
- If pos == 0, increment ans.
- Return ans.
Complexity Analysis
Time: O(n), where n is the length of nums.
Space: O(1).
Common Pitfalls
- Only checking whether final position is zero (wrong; we need count of all visits).
- Counting the initial position before any move (not required).
- Forgetting negative values also move the ant and affect the prefix sum.
Reference Implementations (Java / Go / C++ / Python / JavaScript)
class Solution {
public int returnToBoundaryCount(int[] nums) {
int pos = 0;
int ans = 0;
for (int x : nums) {
pos += x;
if (pos == 0) {
ans++;
}
}
return ans;
}
}func returnToBoundaryCount(nums []int) int {
pos, ans := 0, 0
for _, x := range nums {
pos += x
if pos == 0 {
ans++
}
}
return ans
}class Solution {
public:
int returnToBoundaryCount(vector<int>& nums) {
int pos = 0, ans = 0;
for (int x : nums) {
pos += x;
if (pos == 0) {
ans++;
}
}
return ans;
}
};class Solution:
def returnToBoundaryCount(self, nums: List[int]) -> int:
pos = 0
ans = 0
for x in nums:
pos += x
if pos == 0:
ans += 1
return ansvar returnToBoundaryCount = function(nums) {
let pos = 0;
let ans = 0;
for (const x of nums) {
pos += x;
if (pos === 0) {
ans++;
}
}
return ans;
};中文
题目概述
给定数组 nums,蚂蚁初始位置为 0,按顺序执行每一步位移。请统计:在每次移动之后,蚂蚁回到位置 0 的次数。
核心思路
本质是前缀和计数。用 pos 维护当前累计位置(即移动前缀和),每当 pos == 0,说明回到边界一次。
算法步骤
- 初始化 pos = 0、ans = 0。
- 遍历 nums 中每个位移 x,执行 pos += x。
- 若 pos == 0,则 ans++。
- 遍历结束后返回 ans。
复杂度分析
时间复杂度:O(n)。
空间复杂度:O(1)。
常见陷阱
- 只判断最后位置是否为 0(错误,题目要的是过程中回到 0 的总次数)。
- 把初始位置 0 也算进答案(通常不算,必须是“移动之后”)。
- 忽略负数位移对累计位置的影响。
多语言参考实现(Java / Go / C++ / Python / JavaScript)
class Solution {
public int returnToBoundaryCount(int[] nums) {
int pos = 0;
int ans = 0;
for (int x : nums) {
pos += x;
if (pos == 0) {
ans++;
}
}
return ans;
}
}func returnToBoundaryCount(nums []int) int {
pos, ans := 0, 0
for _, x := range nums {
pos += x
if pos == 0 {
ans++
}
}
return ans
}class Solution {
public:
int returnToBoundaryCount(vector<int>& nums) {
int pos = 0, ans = 0;
for (int x : nums) {
pos += x;
if (pos == 0) {
ans++;
}
}
return ans;
}
};class Solution:
def returnToBoundaryCount(self, nums: List[int]) -> int:
pos = 0
ans = 0
for x in nums:
pos += x
if pos == 0:
ans += 1
return ansvar returnToBoundaryCount = function(nums) {
let pos = 0;
let ans = 0;
for (const x of nums) {
pos += x;
if (pos === 0) {
ans++;
}
}
return ans;
};
Comments