Question
Write a method that accepts an array and a number k and prints all pairs of numbers in array whose sum equals k Sample Runs
Write a method that accepts an array and a number k and prints all pairs of numbers in array whose sum equals k
Sample Runs
Input : arr[] = {1, 5, 7, -1}, sum = 6
Output : Pairs with sum 6 are (1, 5) (7, -1)
Input : arr[] = {1, 5, 7, -1, 5}, sum = 6
Output : Pairs with sum 6 are (1, 5), (7, -1) (1, 5)
Order of output does not matter
Hint: Same idea as before, use an auxillary set. When iterating over the array, check if its complement is present in the set. If yes, print both of them. If not do nothing. In both cases add the current element to the set before moving on
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started