Skip to content

Instantly share code, notes, and snippets.

@manojnaidu619
Last active April 11, 2020 08:01
Show Gist options
  • Save manojnaidu619/34feec4545961b712e479c0745f8c621 to your computer and use it in GitHub Desktop.
Save manojnaidu619/34feec4545961b712e479c0745f8c621 to your computer and use it in GitHub Desktop.
Print all subarrays whose sum equals k in python
nums = [3,4,-7,3,1,3,1,-4,-2,-2] # Change the array here
k = 0 # Change the sum value here
hashmap = {0:[-1]}
cumsum = 0
def printsubarray(indexarray, index):
for x in indexarray:
print(nums[x+1:index+1])
for x in range(0,len(nums)):
cumsum += nums[x]
if cumsum-k in hashmap:
printsubarray(hashmap[cumsum-k], x)
if cumsum in hashmap:
hashmap.get(cumsum).append(x)
else:
hashmap[cumsum] = [x]
# Time complexity : O(n)
# Space complexity : O(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment