Python
- key differences between List and Arrays
- Python collections ChainMap
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python collections
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions in Python
- key differences between List and Arrays
- Program: Calculate Pi in Python
- String Formatting in Python
- Python counters
- python tuples
- Python deque
- Python dictionary
- Python Lists
- python namedtuple
Find all the pairs whose sum is equal to a given number
#For a given integer array, find all the pairs whose sum is equal to a given number.
def find_pairs(array, target_sum):
pairs = []
Sort the array to enable two-pointer approach
array.sort()
left = 0
right = len(array) - 1
while left < right:
current_sum = array[left] + array[right]
if current_sum == target_sum:
pair = (array[left], array[right])
pairs.append(pair)
# Move the pointers to find other possible pairs
left += 1
right -= 1
elif current_sum < target_sum:
left += 1
else:
right -= 1
return pairs
array = [2, 4, 1, 5, 3, 8, 7]
target_sum = 9
result = find_pairs(array, target_sum)
print(result)
Output: [(1, 8), (2, 7), (3, 6), (4, 5)]