Introduction
This question was asked in a technical interview, I am looking for some feedback on my solution.
Given a list of integers and a number K, return which contiguous elements of the list sum to K. For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should return [2, 3, 4].
The Ask
My solution works with my test cases, but I would like feedback on how others would approach the problem and where my code could be altered to improve efficiency and runtime. Currently, I have a nested for loop and I believe my solution is O(n2).
Solution
def contigSum(nums, k):
for i, num in enumerate(nums):
accum = 0
result = []
# print(f'Current index = {i}')
# print(f'Starting value = {num}')
for val in nums[i:len(nums)]:
# print(f'accum = {accum}')
result.append(val)
# print(f'accum = {accum} + {val}')
accum += val
if accum == k:
print(f'{result} = {k}')
return 0
# else:
# print(f'accum = {accum}')
print('No match found')
return 1
Test Cases
nums0 = []
k0 = None
contigSum(nums0, k0)
nums6 = [1, 2, 3]
k6 = 99
contigSum(nums6, k6)
nums1 = [1, 2, 3, 4, 5]
k1 = 9
contigSum(nums1, k1)
nums2 = [-1, -2, -3]
k2 = -6
contigSum(nums2, k2)
nums4 = [5, 2, 6, 11, 284, -25, -2, 11]
k4 = 9
contigSum(nums4, k4)
nums5 = [10, 9, 7, 6, 5, 4, 3, 2 ,1]
k5 = 20
contigSum(nums5, k5)