Scrivio Interview library
Arrays and hashingHashing and hash mapsReported 34 times · 15 min read · updated 15 November 2026

Count the pairs of elements in an array that add up to a target sum.

1What it means to count the pairs that add up to a target

Imagine a small party where every guest is handed a numbered ticket as they walk in, and two guests win a prize together if their two numbers add up to 6. The host stands at the door with a notebook. Each time a guest arrives, the host checks the notebook to see how many guests already inside hold the number that would complete a 6, then writes down the new guest's own number. By the time the last guest arrives, the host has found every winning pair without ever walking round the room. That notebook is the whole idea of this article.

The problem in plain words is this. We are given an array of whole numbers and a target, and we must count the pairs of positions whose values add up to the target. A pair means two different positions, i and j, with i before j. So the same value at two positions can take part in different pairs, an element never pairs with itself, and the pair (i, j) is the same as (j, i), so we count it once.

Let us keep one example, the array {1, 5, 7, -1, 5} with target 6, and work it by hand. Take each position and look to its right for a partner. The 1 at index 0 pairs with the 5 at index 1 and with the 5 at index 4, two pairs. The 5 at index 1 would need a 1 to its right, and there is none. The 7 at index 2 pairs with the -1 at index 3. Nothing else adds up. So the answer is 3.

PictureThe example array and its three pairs

The array {1, 5, 7, -1, 5} with target 6. Three pairs of positions add up to 6.

  1. 105172-1354
    target
    6
    pair 1
    a[0] + a[1] = 1 + 5
    pair 2
    a[2] + a[3] = 7 + -1
    pair 3
    a[0] + a[4] = 1 + 5
    expected
    3

    1With target 6 there are three pairs of positions: 1 and 5 at indexes 0 and 1, 7 and -1 at indexes 2 and 3, and 1 and the second 5 at indexes 0 and 4.

What to assume

Do we count pairs of positions or pairs of distinct values?
We count positions, so {1, 1, 1, 1} with target 2 gives 6.
Is the array sorted?
No.
Can values be negative?
Yes, as the -1 shows.
Can the count be large?
Yes, so we return a long.

This problem can feel tricky because of the duplicates, but it is smaller than it looks. For each element, the only number that can complete a pair is fixed: it is the target minus that element, which we call its complement. For the 5 the complement is 1, for the 7 it is -1. So the whole job comes down to asking, for each element, how many times its complement has appeared, which is the host's question at the door.

A careful candidate asks a few questions first. Do we count pairs of positions or pairs of distinct values? We count positions, so {1, 1, 1, 1} with target 2 gives 6, and we cover the other meaning at the end. Is the array sorted? No, which matters for the method. Can values be negative? Yes, as the -1 shows. Can the count be large? Yes, so we return a long.

2How to spot the complement look-up pattern

Most beginners read this question and reach for two loops, one to choose the first element and one to try every second element. That is exactly what a careful person does by hand, and we will write it next. Before we do, let us read the question slowly, because its words hint at something much faster, and take the clues one at a time.

The first clue is the word pair together with a fixed target. Once one element of a pair is chosen, the other is no longer free: it must equal the target minus the first. So we are not really searching among all pairs; for each element we are looking for one particular value. Searching for a particular value is something a lookup table does in a single step.

The second clue is the word count, together with the fact that values may repeat. We do not only need to know whether the complement exists, but how many times it has appeared. That tells us what to store for each value: not a yes or no, but a number.

The third clue is that the array is not sorted. On a sorted array, two fingers walking in from both ends can find pairs without extra memory, but on an unsorted array they would need a sort first. With no order to lean on, remembering what we have seen is the natural tool.

Together these clues point to the arrays and hashing family, and to a technique called complement look-up. A hash map is a container of key and value pairs that finds the value for a key almost instantly, like the host's notebook. Here the key is a value from the array and the stored value is how many times it has appeared so far. The rule to carry to new problems is this: when two things must combine to a known total, do not search for the second one, look it up.

Some patterns look similar but do not fit. Two pointers fit a sorted array, as we said. A sliding window, a stretch of neighbouring positions, does not fit either, because the two elements of a pair can be anywhere in the array, not next to each other.

3The honest first attempt, a brute force over every pair

The first solution anyone would write is a brute force that tries every pair. The outer loop picks i, the inner loop picks every j after i, and we add 1 to the count whenever a[i] + a[j] equals the target. Starting j at i + 1 does two jobs at once: an element never pairs with itself, and each pair is tried only once. It is clearly correct, and it makes a useful checker for any faster method.

Java
static long countPairsSlow(int[] a, int target) {
long pairs = 0;
for (int i = 0; i < a.length; i++)
for (int j = i + 1; j < a.length; j++) // every pair i < j, once
if ((long) a[i] + a[j] == target) pairs++;
return pairs;
}

Let us count its work on the example. With five elements, i = 0 tries four partners, i = 1 tries three, i = 2 tries two, and i = 3 tries one, so 4 + 3 + 2 + 1 = 10 additions. For n elements that is n times (n - 1) / 2 additions, which grows like n squared, so the time is O(n^2), read as order n squared. For 100,000 elements that is about five billion additions. The extra memory, called the space, is only a counter, which we write O(1).

So where is the waste? Look at the second 5, at index 4. When the inner loop reaches it, it is compared against 1, 5, 7 and -1, one at a time, to find out how many of them equal its complement, 1. But the answer to that question is just a count of one value among the elements before it, and that count could have been written down as we went. The brute force keeps asking the room; the host simply checks the notebook.

So the question that leads further is this. If we walk the array once from left to right and keep, for every value, how many times we have seen it so far, can each element find its earlier partners with a single look-up?

4Getting to the one-pass solution, one observation at a time

The first observation is about who counts a pair. Every pair has an earlier element and a later element. If we let the later element do the counting, each pair is counted exactly once, at the moment its later element is reached. So as we walk, each element x only has to count its partners among the elements before it.

The second observation is that those earlier partners are exactly the earlier elements equal to target - x. If a map called seen holds, for each value, how many times it has appeared so far, then x has seen.getOrDefault(target - x, 0) earlier partners. getOrDefault returns the stored count, or 0 if the value has never appeared. We add that number to the total, and then we record x itself with seen.merge(x, 1, Integer::sum), which adds 1 to its count.

Here is the question a beginner asks. Does it matter whether we record x before or after the look-up? Let us try recording first and see what goes wrong. Take the array {3, 4} with target 6. At x = 3 we record 3, then look up 6 - 3 = 3, and the map says one 3 has been seen, so we count a pair. But that 3 is x itself, and an element must not pair with itself. The true answer is 0. Looking up first means the map only ever holds elements strictly before x, which is exactly the set of possible earlier partners.

Duplicates now take care of themselves. In {1, 1, 1, 1} with target 2, the second 1 finds one earlier 1, the third finds two, and the fourth finds three, so the total is 1 + 2 + 3 = 6, the number of pairs of positions. The counts in the map are what make this right; a set that only remembered whether a value existed would give 3.

One more detail protects us at the edges. If the target is Integer.MIN_VALUE and x is 1, then target - x in int arithmetic wraps round to a large positive number, because an int cannot hold the true result. So we compute need = (long) target - x, and use Long keys in the map. A tempting slip is to store Integer keys and look up a Long: Long 5 and Integer 5 are not equal as map keys, so every look-up would quietly return 0. That is why we record (long) x as well.

Why is the method correct? At the moment we reach position j, the map holds the counts of exactly the elements at positions 0 to j - 1, so the number we add is the number of i before j with a[i] + a[j] equal to the target. Adding this for every j counts every pair once, by its later element.

5Watching the map count pairs on the example

The picture plays the loop on {1, 5, 7, -1, 5} with target 6. The pointer i marks the element we are handling. Elements already recorded in the map are marked as done, and the earlier elements that equal the complement, the partners being counted, are marked as compared. The panel shows x, the value we need, how many partners were found, the running total and the map.

Watch the order inside each step, because the look-up always happens before x joins the map.

Step throughCounting pairs that sum to 6 in one pass

Done cells are recorded in the map. Compared cells are the earlier partners of the current element.

  1. 105172-1354i
    target
    6
    pairs
    0
    seen
    empty

    1We start with an empty map and a pair count of 0. The map will remember how many times each value has appeared so far.

  2. 105172-1354i
    x
    1
    need
    6 - 1 = 5
    found
    0
    pairs
    0
    seen
    1:1

    2We look at a[0] = 1. Its partner would be 6 - 1 = 5, and the map is empty, so no earlier element pairs with it. Only then do we record 1 in the map.

  3. 105172-1354i
    x
    5
    need
    6 - 5 = 1
    found
    1
    pairs
    1
    seen
    1:1 5:1

    3a[1] = 5 needs 6 - 5 = 1. The map says one 1 has been seen, so 5 pairs with it and the count becomes 1. Then we record the 5.

  4. 105172-1354i
    x
    7
    need
    6 - 7 = -1
    found
    0
    pairs
    1
    seen
    1:1 5:1 7:1

    4a[2] = 7 needs -1. No -1 has been seen yet, so nothing is added. The pair 7 and -1 will be counted later, when the -1 arrives.

  5. 105172-1354i
    x
    -1
    need
    6 - -1 = 7
    found
    1
    pairs
    2
    seen
    1:1 5:1 7:1 -1:1

    5a[3] = -1 needs 7, and the map holds one 7, so we add 1 and the count becomes 2. Each pair is counted by its later element, so never twice.

  6. 105172-1354i
    x
    5
    need
    6 - 5 = 1
    found
    1
    pairs
    3
    seen
    1:1 5:2 7:1 -1:1

    6a[4] = 5 needs 1 again. The same 1 at index 0 is still in the map, so the second 5 forms a new pair with it, and the count becomes 3.

  7. 105172-1354
    target
    6
    pairs
    3
    seen
    1:1 5:2 7:1 -1:1

    7The loop has finished after five steps, one per element, and the answer is 3, the same three pairs we found by hand.

Let us read the important frames back. In the second frame the 1 finds nothing, because the map is empty, and only afterwards does 1 enter the map. In the third frame the 5 needs a 1, finds one, and the total becomes 1. In the fourth frame the 7 needs a -1 that has not arrived, so nothing happens yet; the pair is counted in the fifth frame, by the -1, its later element.

The sixth frame is the one worth pausing on. The second 5 needs a 1, and the same 1 at index 0 is still in the map, so it counts a second pair with it. The pairs (0, 1) and (0, 4) share an element but are different pairs of positions, and both belong in the answer, which ends at 3.

6The complete Java program

Here is the full program. It holds the one-pass method and the brute force beside it, so that main can confirm both give 3 on the example. main also runs the duplicates case, the {3, 4} case where a 3 must not pair with itself, and an empty array, and the comment on each line shows what it prints.

Java
import java.util.HashMap;
import java.util.Map;
public class CountPairs {
// For each element, every earlier element equal to target - x forms one pair with it.
static long countPairs(int[] a, int target) {
Map<Long, Integer> seen = new HashMap<>(); // value -> how many times seen so far
long pairs = 0;
for (int x : a) {
long need = (long) target - x; // long: no overflow at the extremes
pairs += seen.getOrDefault(need, 0); // pair x with each earlier partner
seen.merge((long) x, 1, Integer::sum); // only now count x itself
}
return pairs;
}
// Brute force, for checking: every pair i < j.
static long countPairsSlow(int[] a, int target) {
long pairs = 0;
for (int i = 0; i < a.length; i++)
for (int j = i + 1; j < a.length; j++)
if ((long) a[i] + a[j] == target) pairs++;
return pairs;
}
public static void main(String[] args) {
System.out.println(countPairs(new int[] {1, 5, 7, -1, 5}, 6)); // 3
System.out.println(countPairs(new int[] {1, 1, 1, 1}, 2)); // 6
System.out.println(countPairs(new int[] {3, 4}, 6)); // 0
System.out.println(countPairs(new int[] {}, 4)); // 0
System.out.println(countPairsSlow(new int[] {1, 5, 7, -1, 5}, 6)); // 3
}
}

Let us read countPairs in the order it runs. First we create seen, an empty HashMap from Long values to how many times each has appeared, and pairs, the total, as a long because the number of pairs can grow like n squared and overflow an int.

The loop takes each x in turn. need = (long) target - x is the complement, computed in long so that it cannot wrap round. pairs += seen.getOrDefault(need, 0) adds the number of earlier partners, which is 0 for a value never seen. Only then does seen.merge((long) x, 1, Integer::sum) record x, putting 1 for a new value or adding 1 to an existing count. When the loop ends, pairs holds the answer.

countPairsSlow is the brute force from earlier, kept for checking. The output reads 3 for the example, 6 for four 1s with target 2, 0 for {3, 4} with target 6, 0 for the empty array, and 3 again from the brute force.

7How much it costs, and the cases at the edges

Let us count on the example first. The loop ran five times, and each time it did one look-up and one update in the map, so ten map operations, against ten additions for the brute force. That looks like a tie, but it is only because the array is tiny. For n elements we do 2n map operations, each taking constant time on average, so the time is O(n), while the brute force grows like n squared.

The space is the map. It holds one entry per distinct value, four for our example, since 5 appears twice. In the worst case every value is different, so the space is O(n).

Comparing the ways to count pairs
ApproachTimeExtra spaceNote
Every pair with two loopsO(n^2)O(1)simple checker
Sort, then two pointersO(n log n)O(1) to O(log n)runs of equal values need care
One pass with a map of countsO(n)O(n)look up first, then record

The edge cases are handled by the same loop. An empty array or a single element gives 0, because no element finds an earlier partner. An element equal to half the target, such as 3 with target 6, never pairs with itself, because we look up before we record. All-equal arrays give large answers, which is why pairs is a long. Values near the int limits are safe, because need is computed in long.

8Follow-up questions

How would you count pairs of distinct values instead of pairs of positions?

First build a map of value counts for the whole array. Then go through each distinct value v and its complement w = target - v. If v is smaller than w and both are present, that value pair counts once. If v equals w, the pair counts once only if v appears at least twice. Checking only v smaller than w stops us counting the same value pair twice. So {1, 1, 1, 1} with target 2 gives 1 instead of 6.

Can you do it without the extra memory of the map?

Yes, if we may sort the array. After sorting, put one finger at each end. If the two values add up to less than the target, the left finger moves right to a bigger value; if more, the right finger moves left. When they match, we must count runs of equal values: if the two values differ, the pairs are the length of the left run times the length of the right run, and if they are equal, every pair inside the run counts, r times (r - 1) / 2. Sorting costs O(n log n) time, and the walk itself needs no map.

What if the interviewer asks for the pairs themselves, not only how many?

Then the map stores lists of indexes instead of counts. For each x we take the list stored under its complement and output one pair for each index in it, then add the current index to the list under x. The time becomes O(n plus the number of pairs), because in an array such as all 1s the number of pairs itself can grow like n squared, and we cannot print them faster than that.

9Conclusion

We counted the pairs that add up to a target in one pass. For each element x we look up how many earlier elements equal target - x, add that number, and only then record x in a map of counts, so every pair is counted once by its later element and an element never pairs with itself. It takes O(n) time and O(n) space. The clue to remember is two things that must combine to a known total in an unsorted array: look up the complement instead of searching for it.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm the definition first. I count pairs of positions i before j whose values add up to the target, so duplicates form separate pairs and an element never pairs with itself, and the array is unsorted and may contain negatives.

Then, if they want more

Two nested loops over every pair work, but that is O(n^2). The observation is that for each element x, its partner must equal target minus x, so instead of searching I can look the partner up. I walk the array once with a HashMap from value to how many times I have seen it.

For each x I compute need as target minus x in long arithmetic, add seen.getOrDefault of need to the total, and only then increment the count of x.

Looking up before recording means the map holds only earlier elements, so each pair is counted once, by its later element, and a value equal to half the target cannot pair with itself. For {1, 5, 7, -1, 5} with target 6 that gives 3.

Each element costs one look-up and one update, so it is O(n) time and O(n) space, and I return a long because the count can grow quadratically.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 34 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Count the pairs of elements in an array that add up to a target sum.": https://scrivio-interview-library.netlify.app/data-structures/solutions/count-the-pairs-of-elements-in-an-array-that-add-up-to-a-target-0b235d/

More arrays and hashing questions