Drill

ProblemsPython › patterns

The day the account went under

easypatternsPrefix sumsArraysPython

A cash-flow view replays a month of movements and flags the first day the balance dropped below zero.

first_day_under(movements: list<int>) → int

Solve it in the editor →

Where you start

def first_day_under(movements: list[int]) -> int:
    

Worked examples

CallResult
first_day_under([100, -30, -90])3
first_day_under([100, 50])0
first_day_under([-1])1
first_day_under([])0

Hint

This is a running total with one test each step. There is nothing to look back at — you only need the balance so far.

Reference solution in Python
def first_day_under(movements: list[int]) -> int:
    balance = 0
    for i, movement in enumerate(movements):
        balance += movement
        if balance < 0:
            return i + 1
    return 0

The same problem in another language

More patterns problems in Python