Drill

ProblemsTypeScript › patterns

The day the account went under

easypatternsPrefix sumsArraysTypeScript

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

firstDayUnder(movements: list<int>) → int

Solve it in the editor →

Where you start

function firstDayUnder(movements: number[]): number {
  
}

Worked examples

CallResult
firstDayUnder([100,-30,-90])3
firstDayUnder([100,50])0
firstDayUnder([-1])1
firstDayUnder([])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 TypeScript
function firstDayUnder(movements: number[]): number {
  let balance = 0;
  for (let i = 0; i < movements.length; i += 1) {
    balance += movements[i];
    if (balance < 0) return i + 1;
  }
  return 0;
}

The same problem in another language

More patterns problems in TypeScript