- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

True

- Related Questions & Answers
- 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 a number is power of two or not in Python
- Program to check n can be represented as sum of k primes or not in Python
- Python program to check whether a list is empty or not?
- Program to find missing numbers from two list of numbers in Python
- Program to check two rectangular overlaps or not in Python
- Program to check we can find four elements whose sum is same as k or not in Python
- Python program to check whether we can pile up cubes or not
- Program to merge two sorted list to form larger sorted list in Python
- Program to check we can find three unique elements ose sum is same as k or not Python
- Program to count subsets that sum up to k in python
- Program to check number of triplets from an array whose sum is less than target or not Python
- Program to check whether given list is in valid state or not in Python

Advertisements