Back to challenges
Easy 0 solved 0% acceptance

Count Pairs With a Sum

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

What you'll learn

  • Check every pair of positions once
  • Start the inner loop after the outer index
  • Count matches against 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.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Check every earlier-later pair and see whether their sum matches the target.

Hint 2

A straightforward double loop is enough because the input size is small.

Hint 3

Be careful to count each pair once, using positions with i less than j.

Expected complexity

O(n^2) time, O(1) extra space

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.