Last active
April 11, 2020 08:01
-
-
Save manojnaidu619/34feec4545961b712e479c0745f8c621 to your computer and use it in GitHub Desktop.
Print all subarrays whose sum equals k in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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