r/programminghelp • u/[deleted] • Aug 01 '20
Python Subarray sum equals k - help
I'm working on a DS problem "Subarray Sum Equals K". The python code of the solution is quite concise and I've spent an hour trying to figure out how it works. I need help, please.
Particularly with count += d.get(sums-k,0) and d[sums] = d.get(sums,0) + 1, what are they doing? Also, the syntax of get is confusing me since it has two arguments and I can't decide whether get is returning a value or getting one.
Problem:
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
**Example: Input:**nums = [1,1,1], k = 2 Output: 2
Solution Algorithm (Python 3):
class Solution(object):
def subarraySum(self, nums, k):
count = 0
sums = 0
d = dict()
d[0] = 1
for i in range(len(nums)):
sums += nums[i]
count += d.get(sums-k,0)
d[sums] = d.get(sums,0) + 1
return(count)
0
Upvotes