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.

Algorithm

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

The output of the above code is ?

True

How It Works

The algorithm uses the two-pointer technique to find the pair efficiently ?

  • Left pointer (i) starts from the beginning
  • Right pointer (j) starts from the end
  • If sum equals k, we found the pair
  • If sum is less than k, move left pointer right to increase sum
  • If sum is greater than k, move right pointer left to decrease sum

Time and Space Complexity

  • Time Complexity: O(n) where n is the length of the array
  • Space Complexity: O(1) constant space as required

Conclusion

The two-pointer approach efficiently finds if any two numbers in a sorted array sum to a target value k. This solution works in linear time with constant space complexity, making it optimal for the given constraints.

Updated on: 2026-03-26T16:39:38+05:30

693 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements