
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Check if list is sorted or not in Python
- Program to find any two numbers in a list that sums up to k in Python
- Program to check n can be shown as sum of k or not in Python
- Program to check n can be represented as sum of k primes or not in Python
- Program to merge two sorted list to form larger sorted list in Python
- Python program to check whether a list is empty or not?
- Program to check we can find four elements whose sum is same as k or not in Python
- Program to check a number is power of two or not in Python
- Program to find missing numbers from two list of numbers in Python
- Program to check we can find three unique elements ose sum is same as k or not Python
- Program to check two rectangular overlaps or not in Python
- Python program to check whether we can pile up cubes or not
- Program to count subsets that sum up to k in python
- Program to check whether given list is in valid state or not in Python
- Program to check number of triplets from an array whose sum is less than target or not Python

Advertisements