‹ back to the board

Monday, September 28

Adeptalgorithms & data structures

The Granary Ledger of Hollow Mill

The reeve of Hollow Mill audits the granary ledger at the end of every season. The ledger holds one whole number for each day: sacks carried in (positive), sacks carried out (negative), or a still day when nothing moved (zero).

The reeve's question is always the same. Over how many stretches of consecutive days did the granary's stock change by exactly a given amount?

Write countStretches(days, target).

  • days is a list of integers, possibly empty. Values may be negative, positive, or zero.
  • target is an integer.

Return an integer: the number of index pairs (i, j) with 0 <= i <= j < len(days) such that days[i] + days[i+1] + ... + days[j] equals target. A stretch must cover at least one day. Two stretches are different whenever they begin or end on different days, even if they cover the same numbers.

  • hash-map counting
  • Adept
  • efficiency bonus

examples

  1. case 1days of [1, 2, 3, -2, 2], target of 34 — the stretches are days 0..1 (1+2), days 1..3 (2+3-2), day 2 alone (3), and days 2..4 (3-2+2)
  2. case 2days of [0, 0, 0], target of 06 — all six stretches of consecutive days sum to zero
  3. case 3days of [], target of 00 — a stretch must cover at least one day
  4. case 4days of [5], target of 00 — the only stretch sums to 5
reward
360 XP
signature
countStretches
not yet run

TypeScript, run as ES2022 — types are stripped, not checked. If a JS engine would run it, so will we.

loading the editor…
  • the reeve's sample season
  • an empty ledger
  • three still days, target zero
  • a single day that misses
  • a single day that hits
  • carts in and out, target zero
  • losses between the gains
  • nothing matches at all
  • the long still season
The Granary Ledger of Hollow Mill · bitwick