Algorithmic patterns · 9 / 15 Exercise Hard

Subarrays with sum k

Objective

With prefixes and a dictionary you can count in O(n) the consecutive ranges that add up to k: a range adds up to k if the current running sum minus k equals an earlier running sum.

Instructions

  • The first line has integers (they can be negative) and the second the integer k.
  • Show Subarrays: n with how many consecutive (non-empty) ranges add up to k.
Input
1 1 1
2
Output
Subarrays: 2

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise