Ant on the Boundary - 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.

Input & Output

Example 1 — Basic Movement
$ Input: nums = [2,-3,3,-4]
Output: 0
💡 Note: Ant moves: start(0) → +2(2) → -3(-1) → +3(2) → -4(-2). Never returns to position 0.
Example 2 — Return to Boundary
$ Input: nums = [3,-3,4,-4]
Output: 2
💡 Note: Ant moves: start(0) → +3(3) → -3(0) → +4(4) → -4(0). Returns to boundary twice.
Example 3 — No Returns
$ Input: nums = [1,2,3]
Output: 0
💡 Note: Ant moves: start(0) → +1(1) → +2(3) → +3(6). Always moving right, never returns to 0.

Constraints

  • 1 ≤ nums.length ≤ 50
  • -100 ≤ nums[i] ≤ 100
  • nums[i] ≠ 0

Visualization

Tap to expand
Ant on the Boundary INPUT Boundary (0) Ant LEFT RIGHT nums array: 2 [0] -3 [1] 3 [2] -4 [3] Rules: - Positive: move RIGHT - Negative: move LEFT - Count boundary returns ALGORITHM STEPS 1 pos=0, add 2 pos = 0+2 = 2 (not 0) 2 pos=2, add -3 pos = 2+(-3) = -1 (not 0) 3 pos=-1, add 3 pos = -1+3 = 2 (not 0) 4 pos=2, add -4 pos = 2+(-4) = -2 (not 0) Position Tracking: 0 2 -1 -2 Positions: 0 --> 2 --> -1 --> 2 --> -2 Never reaches 0 after start! Approach: Prefix Sum = 0 count FINAL RESULT Boundary Returns Count: 0 The ant never returned to the boundary! Summary Step 1: pos = 2 X Step 2: pos = -1 X Step 3: pos = 2 X Step 4: pos = -2 X Output: 0 Key Insight: Track position as running sum (prefix sum). Each time sum equals 0, the ant is at boundary. Time Complexity: O(n) - single pass through array. Space Complexity: O(1) - only track position. Count occurrences where prefix_sum == 0 (excluding initial position at start). TutorialsPoint - Ant on the Boundary | Optimal Solution (Prefix Sum)
Asked in
Google 15 Amazon 12
5.4K Views
Medium Frequency
~10 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen