Suppose we have a list of numbers called nums and the elements in nums are sorted in ascending order. We also have another value k, we have to check whether any two elements taken from the list add up to k or not. The numbers can also be negative or 0. We have to solve this problem in constant amount of space usage.
So, if the input is like nums = [-8, -3, 2, 7, 9] k = 4, then the output will be True, because if we take 7 and -3, then the sum is 7 + (-3) = 4, which is same as k.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
def solve(nums, k): i = 0 j = len(nums) - 1 while i < j: cur_sum = nums[i] + nums[j] if cur_sum == k: return True elif cur_sum < k: i += 1 else: j -= 1 return False nums = [-8, -3, 2, 7, 9] k = 4 print(solve(nums, k))
[-8, -3, 2, 7, 9], 4