Talentd
FleetCode
Make and follow sheets.Sign in

Ant on the Boundary solution and explanation

EasyArrayPrefix SumSimulation5 min read74.6% acceptanceUpdated 9 Apr 2026
3028. Ant on the Boundary | Arrays | Weekly Contest 383Aryan Mittal · 3:58 · 1K viewsWatch on YouTube
9 more videos on this problem
  1. 3028. Ant on the Boundary | Arrays | Weekly Contest 383Aryan Mittal · 3:58 · 1K views
  2. 100214 Ant on the Boundary || leetcode || contest 383 || solved || javaSsquare · 0:49 · 998 views
  3. Leetcode | 3028. Ant on the Boundary | Easy | Java SolutionDeveloper Docs · 3:42 · 628 views
  4. Ant On The Boundary - Python - Leetcode 3028CheatCode Ninja · 2:17 · 274 views
  5. 3028 Ant on the Boundary || for Beginners 🔥 || Prefix sum ✅Ayush Rao · 2:42 · 247 views
  6. 3028. Ant on the Boundary (Leetcode Easy)Programming Live with Larry · 2:34 · 216 views
  7. Leetcode 3028. Ant on the BoundaryElite Code · 8:35 · 169 views
  8. leetcode 3028 : ant on the boundary : python solutionleetcode blind 75 · 2:13 · 163 views
  9. Leetcode 3028 || Ant on the Boundary || Weekly Contest || EasyKomal Pal · 8:03 · 146 views
  10. my attempt at solving leetcode 3028: ant on the boundary [SOLVED]Cameron Late · 5:00 · 139 views

The problem

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.

Notes:

  • There is an infinite space on both sides of the boundary.
  • We check whether the ant is on the boundary only after it has moved |nums[i]| units. In other words, if the ant crosses the boundary during its movement, it does not count.

Example 1:

Input: nums = [2,3,-5]
Output: 1
Explanation: After the first step, the ant is 2 steps to the right of the boundary.
After the second step, the ant is 5 steps to the right of the boundary.
After the third step, the ant is on the boundary.
So the answer is 1.

Example 2:

Input: nums = [3,2,-3,-4]
Output: 0
Explanation: After the first step, the ant is 3 steps to the right of the boundary.
After the second step, the ant is 5 steps to the right of the boundary.
After the third step, the ant is 2 steps to the right of the boundary.
After the fourth step, the ant is 2 steps to the left of the boundary.
The ant never returned to the boundary, so the answer is 0.

Constraints:

  • 1 <= nums.length <= 100
  • -10 <= nums[i] <= 10
  • nums[i] != 0

Approach overview

Problem Overview: An ant starts at position 0 on a number line. You receive an array nums where each value represents a movement. After applying each move sequentially, count how many times the ant lands exactly back on position 0.

Approach 1: Cumulative Position Tracking (O(n) time, O(1) space)

This approach directly simulates the ant’s movement using a running prefix sum. Start with a variable position = 0 and iterate through the array. For each step, add the move value to position. Every time position == 0, increment the answer counter. The key insight is that the ant’s location after each move is simply the cumulative sum of all previous moves. Since you only track a single integer and iterate once through the array, the solution runs in O(n) time with O(1) extra space. This pattern commonly appears in problems involving Prefix Sum and Simulation.

Approach 2: Pre-calculation of Positions (O(n) time, O(n) space)

Instead of updating a single running variable, this approach builds an explicit prefix array of positions. Create an array pos where pos[i] stores the ant’s position after the i-th move. Compute each entry using pos[i] = pos[i-1] + nums[i]. After constructing the prefix array, iterate through it and count how many values equal zero. This approach still runs in O(n) time but requires O(n) space to store intermediate positions. It can be useful if you need the full position history for debugging, visualization, or follow-up queries. The technique is a direct application of prefix accumulation on an Array.

Recommended for interviews: Cumulative Position Tracking. Interviewers expect you to recognize that the ant’s location is just a running prefix sum. The brute-style prefix array approach demonstrates understanding, but the constant-space simulation shows stronger problem-solving efficiency.

Approach 1: Approach 1: Cumulative Position Tracking

The simplest way to solve this problem is by keeping track of the ant's cumulative position as it traverses the nums array. At each step, we update the cumulative position based on the value of nums[i]. If this cumulative position becomes zero, it indicates that the ant has returned to the boundary.

def count_boundary_returns(nums):
    position = 0
    return_count = 0
    for num in nums:
        position += num
        if position == 0:
            return_count += 1
    return return_count

print(count_boundary_returns([2, 3, -5]))  # Output: 1
public class AntBoundary {
    public static int countBoundaryReturns(int[] nums) {
        int position = 0, returnCount = 0;
        for (int num : nums) {
            position += num;
            if (position == 0) returnCount++;
        }
        return returnCount;
    }

    public static void main(String[] args) {
        int[] nums = {2, 3, -5};
        System.out.println(countBoundaryReturns(nums));  // Output: 1
    }
}
#include <vector>
#include <iostream>

int countBoundaryReturns(const std::vector<int>& nums) {
    int position = 0, returnCount = 0;
    for (int num : nums) {
        position += num;
        if (position == 0) returnCount++;
    }
    return returnCount;
}

int main() {
    std::vector<int> nums = {2, 3, -5};
    std::cout << countBoundaryReturns(nums);  // Output: 1
    return 0;
}
function countBoundaryReturns(nums) {
    let position = 0;
    let returnCount = 0;
    for (let num of nums) {
        position += num;
        if (position === 0) returnCount++;
    }
    return returnCount;
}

console.log(countBoundaryReturns([2, 3, -5]));  // Output: 1
#include <stdio.h>

int countBoundaryReturns(int* nums, int numsSize) {
    int position = 0, returnCount = 0;
    for (int i = 0; i < numsSize; i++) {
        position += nums[i];
        if (position == 0) returnCount++;
    }
    return returnCount;
}

int main() {
    int nums[] = {2, 3, -5};
    int size = sizeof(nums) / sizeof(nums[0]);
    printf("%d", countBoundaryReturns(nums, size));  // Output: 1
    return 0;
}
using System;

public class AntBoundary
{
    public static int CountBoundaryReturns(int[] nums)
    {
        int position = 0, returnCount = 0;
        foreach (int num in nums)
        {
            position += num;
            if (position == 0) returnCount++;
        }
        return returnCount;
    }

    public static void Main()
    {
        int[] nums = {2, 3, -5};
        Console.WriteLine(CountBoundaryReturns(nums));  // Output: 1
    }
}

Initialize position and returnCount, iterate through the nums array while updating and checking if the current position matches the boundary condition. Return final count.

Complexity

Time Complexity: O(n)
Space Complexity: O(1)

Try this approach in the editor

Approach 2: Approach 2: Pre-calculation of Positions

This approach involves calculating the position at every step in advance and checking if it has reached zero. Here, we maintain an array of positions to precompute the effect of each action on ant movement.

def count_boundary_returns(nums):
    return_count = 0
    positions = [0] * (len(nums) + 1)
    for i in range(len(nums)):
        positions[i + 1] = positions[i] + nums[i]
        if positions[i + 1] == 0:
            return_count += 1
    return return_count

print(count_boundary_returns([2, 3, -5]))  # Output: 1
public class AntBoundary {
    public static int countBoundaryReturns(int[] nums) {
        int returnCount = 0;
        int[] positions = new int[nums.length + 1];
        positions[0] = 0;
        for (int i = 0; i < nums.length; i++) {
            positions[i + 1] = positions[i] + nums[i];
            if (positions[i + 1] == 0) returnCount++;
        }
        return returnCount;
    }

    public static void main(String[] args) {
        int[] nums = {2, 3, -5};
        System.out.println(countBoundaryReturns(nums));  // Output: 1
    }
}
#include <vector>
#include <iostream>

int countBoundaryReturns(const std::vector<int>& nums) {
    std::vector<int> positions(nums.size() + 1, 0);
    int returnCount = 0;
    for (size_t i = 0; i < nums.size(); ++i) {
        positions[i + 1] = positions[i] + nums[i];
        if (positions[i + 1] == 0) returnCount++;
    }
    return returnCount;
}

int main() {
    std::vector<int> nums = {2, 3, -5};
    std::cout << countBoundaryReturns(nums);  // Output: 1
    return 0;
}
function countBoundaryReturns(nums) {
    let positions = Array(nums.length + 1).fill(0);
    let returnCount = 0;
    for (let i = 0; i < nums.length; i++) {
        positions[i + 1] = positions[i] + nums[i];
        if (positions[i + 1] === 0) returnCount++;
    }
    return returnCount;
}

console.log(countBoundaryReturns([2, 3, -5]));  // Output: 1
#include <stdio.h>

int countBoundaryReturns(int* nums, int numsSize) {
    int returnCount = 0;
    int positions[numsSize + 1];
    positions[0] = 0;

    for (int i = 0; i < numsSize; i++) {
        positions[i + 1] = positions[i] + nums[i];
        if (positions[i + 1] == 0) returnCount++;
    }
    return returnCount;
}

int main() {
    int nums[] = {2, 3, -5};
    int size = sizeof(nums) / sizeof(nums[0]);
    printf("%d", countBoundaryReturns(nums, size));  // Output: 1
    return 0;
}
using System;

public class AntBoundary
{
    public static int CountBoundaryReturns(int[] nums)
    {
        int[] positions = new int[nums.Length + 1];
        int returnCount = 0;
        positions[0] = 0;
        for (int i = 0; i < nums.Length; i++)
        {
            positions[i + 1] = positions[i] + nums[i];
            if (positions[i + 1] == 0)
                returnCount++;
        }
        return returnCount;
    }

    public static void Main()
    {
        int[] nums = {2, 3, -5};
        Console.WriteLine(CountBoundaryReturns(nums));  // Output: 1
    }
}

Create a positions list to store cumulative position of ant. Checking zero positions and adjust counter accordingly.

Complexity

Time Complexity: O(n)
Space Complexity: O(n)

Try this approach in the editor

Approach 3: Prefix Sum

Based on the problem description, we only need to calculate how many zeros are in all prefix sums of nums.

The time complexity is O(n), where n is the length of nums. The space complexity is O(1).

function returnToBoundaryCount(nums: number[]): number {
    let [ans, s] = [0, 0];
    for (const x of nums) {
        s += x;
        ans += s === 0 ? 1 : 0;
    }
    return ans;
}
func returnToBoundaryCount(nums []int) (ans int) {
	s := 0
	for _, x := range nums {
		s += x
		if s == 0 {
			ans++
		}
	}
	return
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Cumulative Position Tracking

Time Complexity: O(n)
Space Complexity: O(1)

Approach 2: Pre-calculation of Positions

Time Complexity: O(n)
Space Complexity: O(n)

Prefix Sum–

Complexity analysis

ApproachTimeSpaceWhen to Use
Cumulative Position TrackingO(n)O(1)Best general solution. Minimal memory and simple single-pass logic.
Pre-calculation of PositionsO(n)O(n)Useful when you need the full history of positions for debugging or additional queries.

Frequently asked questions

Is Ant on the Boundary easy or hard?

Ant on the Boundary is classified as an Easy problem on LeetCode with a high acceptance rate around 74%. The main challenge is recognizing that the ant's position is simply the prefix sum of the movement array.

Ant on the Boundary Python/Java solution

In both Python and Java, the solution iterates through the array while maintaining a running position variable. Each time the cumulative position becomes zero, a counter increases. The implementation is short, runs in O(n) time, and uses O(1) additional space.

How to solve Ant on the Boundary in O(n)?

Maintain a running variable representing the ant's current position. Iterate through the array, add each move to the position, and check if it equals zero after the update. Each step involves constant work, so the entire algorithm runs in O(n) time.

What is the best approach for Ant on the Boundary?

The best approach is cumulative position tracking using a running prefix sum. Iterate through the moves, update the current position, and count how many times it becomes zero. This solution runs in O(n) time and O(1) space, making it the most efficient and interview-friendly method.

Is Ant on the Boundary asked at Google/Amazon/Meta?

Problems involving prefix sums and running cumulative calculations frequently appear in interviews at companies like Amazon, Google, and Meta. While this exact problem may not always appear, the underlying technique—tracking prefix sums and detecting specific states—is commonly tested.

What data structure is used in Ant on the Boundary?

The problem primarily uses arrays and prefix sum logic. Most solutions maintain a single integer representing the cumulative position, though some implementations store prefix positions in an additional array for analysis.

What is the time complexity of Ant on the Boundary?

The optimal solution runs in O(n) time because you process each move exactly once. Space complexity can be O(1) if you maintain only a running position, or O(n) if you store all prefix positions in an auxiliary array.

Comments

Now write it yourselfClose this page and solve Ant on the Boundary in the editor, without looking.
Practise Ant on the Boundary