All challenges
Easy 0 solved 0% acceptance

Count Pairs With a Sum

Count pairs of positions whose values add up to a target.

Problem

Count the pairs of different positions i < j in numbers where numbers[i] + numbers[j] equals target. Use two nested loops.

Implement count_pairs_with_sum(numbers, target).

Input

numbers: The list of integers. target: The sum to look for.

Output

Return the number of pairs.

Constraints

0 ≤ length of numbers ≤ 500; -10,000 ≤ each number, target ≤ 10,000

Examples

Example 1
Input:
target = 6
numbers = [1, 5, 3, 3, 4]

Expected output:
expected = 2
Input:
long long target = 6;
std::vector<long long> numbers = {1, 5, 3, 3, 4};

Expected output:
long long expected = 2;
Input:
long target = 6;
long[] numbers = new long[] {1, 5, 3, 3, 4};

Expected output:
long expected = 2;

Explanation

1 + 5, 3 + 3 (the two 3s at different positions) make 6: 2 pairs.

Example 2
Input:
target = 4
numbers = [2, 2, 2]

Expected output:
expected = 3
Input:
long long target = 4;
std::vector<long long> numbers = {2, 2, 2};

Expected output:
long long expected = 3;
Input:
long target = 4;
long[] numbers = new long[] {2, 2, 2};

Expected output:
long expected = 3;

Explanation

Every pair of the three 2s sums to 4: positions (0,1), (0,2), (1,2) = 3 pairs.

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.