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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!