Program to check sum of two numbers is up to k from sorted List or not in Python


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 −

  • i := 0
  • j := size of nums - 1
  • while i < j, do
    • cur_sum := nums[i] + nums[j]
    • if cur_sum is same as k, then
      • return True
    • otherwise when cur_sum < k, then
      • i := i + 1
    • otherwise,
      • j := j - 1
  • return False

Example

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))

Input

[-8, -3, 2, 7, 9], 4

Output

True

Updated on: 14-Oct-2021

426 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements