Problem 294366 · medium · Phase 02 Linear Data Structures

Longest Balanced Ledger Stretch

hash maps · prefix sums · subarrays

A ledger lists signed transactions (deposits positive, withdrawals negative). A balanced stretch is a contiguous run of transactions whose total is exactly 0. Return the length of the longest balanced stretch, or 0 if there is none.

Examples

Input:  transactions = [3, -1, -2, 5, -5, 2]
Output: 5
Explanation: 3 - 1 - 2 + 5 - 5 = 0 spans five transactions.

Input:  transactions = [1, 2]
Output: 0

Constraints

  • 0 <= len(transactions) <= 10**5
  • -10**6 <= transactions[i] <= 10**6
  • Target complexity: O(n) time.

Goals

  • Turn a subarray-sum question into a prefix-sum lookup
  • Store the first index of each prefix sum
Starting Python…