Matching Gift Cards
Count the pairs of gift cards whose values add up to a target. Duplicates, negatives and 10 000 cards are on the menu.
Statement
Story
The corner shop sells gift cards of many different values. Every evening the cashier pairs up the leftover cards so that each pair is worth exactly the price of the monthly special. How many different pairs can she make?
Task
You are given the values of n cards and a target T. Count the pairs of cards (i, j) with i < j and a[i] + a[j] = T.
Two cards with the same value at different positions are different cards, and a card can never be paired with itself.
Input
- Line 1:
nandT - Line 2:
nintegersa[1] … a[n]
Limits: 1 ≤ n ≤ 10 000, |a[i]| ≤ 10^9, |T| ≤ 2·10^9. Checking all n²/2 pairs is too slow on the largest tests; aim for one pass over the list.
Output
One integer: the number of pairs.
Example
6 10
3 7 5 5 5 2
Output: 4, because 3 + 7 is one pair and the three 5s give 5 + 5 in three different ways.
Sample input
6 10 3 7 5 5 5 2
Hints
Stuck? Hints are optional, and each one lowers the points you earn for solving this challenge.
- Hint 1Costs 5 points
- Hint 2Costs 5 points
Reveal the previous hint first
- Hint 3Costs 10 points
Reveal the previous hint first
Lessons that teach this
Stuck on the ideas rather than the puzzle? These lessons cover what you need.