Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find any two numbers in a list that sums up to k in Python
Suppose we have a list of numbers called nums and we have another number k, we have to check whether any two numbers present in the list add up to k or not. Same elements must not be used twice, and numbers can be negative or 0.
So, if the input is like nums = [45, 18, 9, 13, 12], k = 31, then the output will be True, as 18 + 13 = 31.
Approach
To solve this, we will follow these steps ?
-
temp_set:= a new set - for each
numinnums, do- if
numis intemp_set, then- return True
- add
(k-num)intotemp_set
- if
- return False
Example
Let us see the following implementation to get better understanding ?
class Solution:
def solve(self, nums, k):
temp_set = set()
for num in nums:
if num in temp_set:
return True
temp_set.add(k - num)
return False
ob = Solution()
nums = [45, 18, 9, 13, 12]
k = 31
print(ob.solve(nums, k))
True
How It Works
The algorithm uses a set to store complements. For each number num, we check if it exists in our set. If yes, we found our pair. If not, we add k - num (the complement) to the set. This way, when we encounter the complement later, we'll find it in the set.
Alternative Approach Using Simple Function
def two_sum(nums, k):
seen = set()
for num in nums:
complement = k - num
if complement in seen:
return True
seen.add(num)
return False
# Test the function
nums = [45, 18, 9, 13, 12]
k = 31
result = two_sum(nums, k)
print(f"Two numbers sum to {k}: {result}")
Two numbers sum to 31: True
Testing with Different Cases
def two_sum(nums, k):
seen = set()
for num in nums:
complement = k - num
if complement in seen:
return True
seen.add(num)
return False
# Test cases
test_cases = [
([2, 7, 11, 15], 9), # True: 2 + 7 = 9
([3, 2, 4], 6), # True: 2 + 4 = 6
([3, 3], 6), # True: 3 + 3 = 6
([1, 2, 3], 7), # False: no two numbers sum to 7
([-1, -2, -3, -4, -5], -8) # True: -3 + (-5) = -8
]
for nums, target in test_cases:
result = two_sum(nums, target)
print(f"nums = {nums}, target = {target} ? {result}")
nums = [2, 7, 11, 15], target = 9 ? True nums = [3, 2, 4], target = 6 ? True nums = [3, 3], target = 6 ? True nums = [1, 2, 3], target = 7 ? False nums = [-1, -2, -3, -4, -5], target = -8 ? True
Time and Space Complexity
- Time Complexity: O(n), where n is the number of elements in the list
- Space Complexity: O(n) for the set storage in worst case
Conclusion
The hash set approach efficiently solves the two-sum problem in linear time by storing complements. This method works with negative numbers and prevents using the same element twice, making it optimal for most scenarios.
