First Balanced Cart Position
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
amounts = [1, 7, 3, 6, 5, 6]3amounts = [-3, 2, 1, 0, 0]3amounts = []-1Constraints
0 <= len(amounts) <= 100000-1000000 <= amounts[i] <= 1000000 for every iPositions are zero-based.The input may be empty and may contain negative, zero, or repeated amounts.- Types:
amountsis int[]; result is int
Function signature
def first_balanced_cart_position(amounts: list[int]) -> int
amountslist[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.