Question:
Given K that consists of non-zero, non-negative integers 1 to K, output all the ranges/intervals whose sum is equal to K.
For example, if K is equal to 6, then the output should be [[1,3], [6,6]]
. For [1,3]
, 1+2+3 = 6 and for [6,6]
, 6 = 6.
My Solution
Here is my solution below, but the time complexity I think is O(N2). Is there a more efficient way to do this?
def targetSum(k):
nums = list(range(1,k+1))
res = []
for end in range(len(nums)):
start = 0
while start <= end:
sumhere = sum(nums[start:end+1])
if sumhere == k:
res.append([nums[start], nums[end]])
start+=1
return res
targetSum(6)