PracticeArrays

First Balanced Cart Position

Easy/MediumArraystraversalaccumulationstate tracking Time not estimated Not started

Context

An ecommerce cart records its net line amounts in sequence. Positive values are product charges, while negative values may represent discounts or credits. A cart position is balanced when the total amount before it equals the total amount after it. Find the earliest such position for reviewing the cart layout.

Problem

Given an integer array of cart line amounts, return the zero-based index of the first position whose left-side sum equals its right-side sum. The amount at the chosen position belongs to neither side. If no position satisfies this condition, or if the cart is empty, return -1. Preserve exact integer arithmetic and examine positions from left to right.

Examples

Example 1
Input: amounts = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation: For [1, 7, 3, 6, 5, 6], the executed result is index 3. The final traced prefix_sum and remaining_sum are both 11.
Example 2
Input: amounts = [-3, 2, 1, 0, 0]
Output: 3
Explanation: For [-3, 2, 1, 0, 0], the executed result is index 3. The final traced prefix_sum and remaining_sum are both 0.
Example 3
Input: amounts = []
Output: -1
Explanation: For the empty array, the executed result is -1. The final traced cursor, prefix_sum, and remaining_sum are all 0.

Constraints

  • 0 <= len(amounts) <= 100000
  • -1000000 <= amounts[i] <= 1000000 for every i
  • Positions are zero-based.
  • The input may be empty and may contain negative, zero, or repeated amounts.
  • Types: amounts is int[]; result is int

Function signature

def first_balanced_cart_position(amounts: list[int]) -> int
amounts list[int]
Signed net amounts for the cart's line items, stored in order.
returns int
The zero-based index of the earliest position whose preceding sum equals its following sum, or -1 when no such position exists.

Adapted from MBPP problem task_701 (CC BY 4.0). Rewritten, extended and verified by Iksha.

Approved · t3-abs_101_v314 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1