More Practice
HashMaps and HashSets are useful in a wide variety of challenges. Below is another practice challenge.
Challenge
Given a list of numbers, can you find all the pairs of numbers whose sum equals k?
Input
The provided boilerplate takes 2 parameters: an array ar
, and the special number k
. This is the raw input format:
The first line of input will contain t. t test cases follow, with each case consisting of n, followed by a line with n numbers. The first number on that line is k, and the remaining numbers are the list.
Output
Print the pairs of numbers. Print each pair with the first number followed by the second, and print all the pairs in the order that the second number appears in the list.
Sample Input/Output
Input
1 8 12 1 9 11 13 2 3 7Output
1 11 9 3
12
is the special number. There are 2 pairs with that sum: 1
& 11
and 9
& 3
. 11
appears before 3
in the input, so that pair is printed first.
Full Credit
Solve the problem with only one iteration through the numbers.
Challenge
Print the pairs of numbers that equal k
as described above.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
Paul
Apr 23, 9:01 AMI simply looped through, but I don't yet see how to solve this using a Set or a Hash.
Dan Cseko
Aug 11, 10:13 AM@Paul - Does it help if I say that the number you're looking for is k - N where N is the current item in the loop? A set would help you know if you've already seen the answer to that sum.