#151 · Dictionaries and sets · Advanced · 135 XP · about 22 min
Write count_subarrays(nums, k) that counts the subarrays of nums whose items add up to exactly k. A subarray is a non-empty stretch of neighbouring items, such as nums[2:5]. Two subarrays at different positions count separately, even if they hold the same values.
The numbers can be negative or zero.
count_subarrays([1, 1, 1], 2) # returns 2 count_subarrays([1, 2, 3], 3) # returns 2 count_subarrays([3, -3, 3], 0) # returns 2 count_subarrays([0, 0, 0], 0) # returns 6
In the second example the two subarrays are [1, 2] and [3].
0 <= len(nums) <= 20,000-1,000 <= nums[i] <= 1,000k is between -10**7 and 10**7Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.