HASH-P4

Stretches that add up to k

Practice 4 of 6Hashing8 tests

The problem

A stretch is one or more neighbouring values of a, like a[2], a[3], a[4]. Count the stretches whose values add up to exactly k. Values can be negative.

count_sums([1, 1, 1], 2)        # 2: [1, 1] twice
count_sums([1, 2, 3], 3)        # 2: [1, 2] and [3]
count_sums([1, -1, 0], 0)       # 3: [1, -1], [0], [1, -1, 0]

Limits

  • Up to 200,000 values. There are about n²/2 stretches, so you cannot try them all.

Builds on HASH-6 Counting and grouping.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

8 tests, not run yet
Test results
#TestResultReads · time
1SmallNot run
2Different lengthsNot run
3Negative valuesNot run
4ZerosNot run
5EmptyNot run
6MixedNot run
7Whole list onlyNot run
8200,000 valuesNot run