Quick revision
The short answer
Finding two elements that add up to K is an arrays and hashing problem solved with a hash set in one pass. For each value x we check whether its only possible partner, K - x, has already been seen; if it has, we return the pair, and if not, we add x. That takes O(n) time and O(n) space, against O(n^2) for checking every pair.
The solution
What it costs
| Approach | Time | Extra space | Keeps original order? |
|---|---|---|---|
| Check every pair | O(n^2) | O(1) | yes |
| Sort, then two pointers | O(n log n) | O(1) if sorting in place | no |
| One pass with a hash set | O(n) | O(n) | yes |
What to remember
We found two elements that add up to K by walking the array once with a hash set. Each value x has exactly one possible partner, K - x, so we check whether that partner has already been seen, return the pair if it has, and otherwise remember x. Checking before adding keeps an element from pairing with itself. That is O(n) time and O(n) space, against O(n^2) for every pair. The clue to remember is that each element tells us exactly which value it needs: then a hash lookup replaces the inner loop.
1What the question asks, told as a gift card
Imagine you have a gift card worth exactly 8 and a shelf of items with prices on them. The shop will only accept the card if you buy exactly two items whose prices add up to exactly 8, no more and no less. You walk along the shelf looking at price tags. The question is whether such a pair of items exists, and if it does, which two they are.
The question asks the same thing of an array. We are given whole numbers and a target K, and we must decide whether two different elements add up to K and, if so, return those two values. Two different elements means two different positions in the array. So in [5] with K = 10 we may not use the one 5 twice, while in [5, 5] the two 5s are separate elements and form a fair pair.
Let us use [8, 7, 2, 5, 3, 1] with K = 8 and look by hand. 8 would need a 0, and there is none. 7 needs a 1, and 1 is at the end, so 7 + 1 works. 2 needs a 6, which is missing. 5 needs a 3, which is there, so 5 + 3 works as well. Either pair is a correct answer. For [1, 2, 3] with K = 7, no two values make 7, so the answer is that no pair exists.
Two pairs make 8: 7 + 1 and 5 + 3. Either one is a correct answer.
1With k = 8, the values 7 and 1 add up to 8, and so do 5 and 3. 8 on its own would need a 0, which is not in the array.
What to assume
- Do we return the values or their positions?
- The question says return them, so values.
- Any pair, or a particular one?
- Any pair.
- What if there is none?
- We return an empty array.
- Is the array sorted?
- We assume not.
- Can values be negative or repeated?
- Yes to both.
- How long can it be?
- Perhaps 100,000 elements, which decides how fast we must be.
A careful candidate asks a few questions first. Do we return the values or their positions? The question says return them, so values; positions are a follow-up. Any pair, or a particular one? Any pair. What if there is none? We return an empty array. Is the array sorted? We assume not. Can values be negative or repeated? Yes to both. How long can it be? Perhaps 100,000 elements, which decides how fast we must be.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a question that wants a lookup
When a beginner first reads this question, the plan that comes to mind is to try every pair of elements and check its sum. That is correct, and it is the brute force we will write next. It treats the question as a search over pairs, and that hides a much simpler question inside it.
So let us take the clues one at a time. The first clue is the word two together with a fixed sum. Once we choose one element x, the second element is not free at all. It must be exactly K - x, and nothing else will do. With K = 8, the 7 needs a 1 and the 5 needs a 3. The search for a pair has quietly become a search for one known value.
The second clue is that the array is not sorted. In a sorted array we could find a known value quickly by halving the range, or walk two indexes in from the ends. Unsorted, the only way to find a value by looking is to look everywhere, unless we keep the values somewhere that can be searched faster than the array.
These clues point to the arrays and hashing family. A hash set is a collection that answers the question have I seen this value? almost instantly, however many values it holds. It works like the index at the back of a book: instead of reading every page to find a word, we go straight to the right place. A hash set does this by turning each value into a number called its hash code and using that number to choose a bucket, a small compartment where the value is stored. To check a value, it computes the same bucket and looks only there. The rule to carry to new problems is that when each element tells you exactly which other value it needs, a hash lookup can replace the inner loop.
Some patterns look similar and do not fit as they are. Two pointers, one at each end moving inwards, solves this question beautifully, but only on a sorted array, so here it needs a sort first. A sliding window looks at runs of neighbouring elements, while our two elements can be anywhere.
3The honest first attempt, checking every pair
The first solution anyone writes is the brute force over every pair, which is a good, honest start, because it is clearly correct. For each position i, we try each position j after it. Starting j at i + 1 means each pair is tried exactly once and no element is ever paired with itself. The first pair whose sum is K is returned.
i stays on one element while j walks over every later element. Each inner walk is really a search for the single value k - a[i].
- looking for
- 0
- checks so far
- 5
1With i on 8, the only partner that could work is 0. j still walks over 7, 2, 5, 3 and 1, five checks, and finds nothing.
- looking for
- 1
- checks so far
- 9
- answer
- [7, 1]
2With i on 7, the only partner is 1. j walks over 2, 5 and 3 before reaching 1 at the end, four more checks.
Let us count on the example. With i on 8, j checks 7, 2, 5, 3 and 1, and none adds to 8, five checks. With i on 7, j checks 2, 5 and 3, and then 1, which makes 8, four more. We return [7, 1] after nine checks. If no pair existed, we would try all 15 pairs of six elements. For n elements that is n x (n - 1) / 2 pairs, which grows like n x n, so the time is O(n^2), read as order n squared. For 100,000 elements that is about five billion checks, far too slow. The extra space is O(1).
Where is the waste? The picture makes it plain. While i stays on 8, the only partner that could ever work is 0, and while i stays on 7, the only partner is 1. Each inner loop is a slow search for one exact value, walking the rest of the array to answer a yes or no question. And the searches repeat: every inner loop walks over the same values 2, 5 and 3 again, without remembering anything from the walks before.
4Getting to the hash set, one observation at a time
Let us start from the waste. Each element x needs exactly one partner, K - x, and the brute force finds out whether that partner exists by walking the array. What if, instead, we remembered every value we have already walked past, in a hash set, so that checking for K - x took a single look? Then one walk along the array would be enough.
So we walk the array once, from the left. For each value x we compute need = K - x, the partner it is looking for. If need is in the set, it is a value we passed earlier, so need and x are two different elements that add up to K, and we return them. If need is not in the set, we add x and move on, so that later elements can find x as their partner.
Here a beginner often asks a fair question. We only look backwards, at values already in the set. What if x's partner comes later in the array, as 1 comes after 7? Let us see what happens. When we stand on 7, its partner 1 has not arrived, so the check fails and we add 7. But when we later stand on 1, its partner is 8 - 1 = 7, which is now in the set. Every pair has an earlier element and a later one, and the pair is found when we reach the later one, because the earlier one is already in the set. No pair can slip through.
The order of the two steps inside the loop also matters, and it is the mistake beginners make most. Suppose we added x first and then checked for need. With [5] and K = 10, we would add 5, then look for 10 - 5 = 5, find it, and return [5, 5], using the one 5 twice. By checking before adding, the set only holds earlier elements, so x can never be its own partner. Yet [5, 5] still works, because the first 5 is in the set when the second arrives.
Why is a set lookup so fast? Because it does not search. To check for need, the set computes need's hash code, goes to that one bucket, and compares the few values stored there. With a good hash code each bucket holds only a value or two, so a lookup or an insertion costs about the same whether the set holds ten values or a million. We say it takes O(1) time on average. That is what turns the slow inner loop into one step.
5Watching the set fill up on the example
The picture plays the single walk over [8, 7, 2, 5, 3, 1] with K = 8. The value under x is the one we stand on. Cells already passed are marked as finished, and the panel shows the partner x needs, whether it is in the set, and the set itself after the step.
Watch the set grow by one value at every step, and notice that we never walk backwards over the array. All the remembering is done by the set.
x is the value we stand on. The panel shows the partner it needs and the set of values seen before it.
- k
- 8
- seen
- empty
1We start with an empty set called seen. The target is 8, and we will walk the array once from the left, one value at a time.
- x
- 8
- need
- 0
- in seen?
- no
- seen
- {8}
2x is 8, so its partner would be 8 - 8 = 0. The set is empty, so 0 has not been seen. We add 8 to the set and move on.
- x
- 7
- need
- 1
- in seen?
- no
- seen
- {8, 7}
3x is 7 and it needs 1. The set holds only 8, so 1 is not there. We add 7. Notice that 1 is in the array, but it has not arrived yet.
- x
- 2
- need
- 6
- in seen?
- no
- seen
- {8, 7, 2}
4x is 2 and it needs 6. The set holds 8 and 7, no 6. We add 2, and the set now remembers three values.
- x
- 5
- need
- 3
- in seen?
- no
- seen
- {8, 7, 2, 5}
5x is 5 and it needs 3. The set holds 8, 7 and 2, no 3. We add 5. 3 is coming next, but we cannot know that yet.
- x
- 3
- need
- 5
- in seen?
- yes
- seen
- {8, 7, 2, 5}
6x is 3 and it needs 8 - 3 = 5. The set holds 5, which arrived one step earlier. The lookup succeeds at once, without any scanning.
- answer
- [5, 3]
- values read
- 5 of 6
7We return [5, 3]: need, which came earlier, and x, which is here now. The last value, 1, is never even looked at.
Let us read the important frames back. For 8, 7, 2 and 5, the needed partners are 0, 1, 6 and 3, and none is in the set when we ask, so each value is added in turn. Notice the frame for 7: its partner 1 is in the array, but it has not been reached yet, so the check correctly fails.
The frame for 3 is the moment of success. 3 needs 5, and 5 joined the set one step earlier, so a single lookup finds it. We return [5, 3] after reading five of the six values and never look at the 1.
The brute force returned [7, 1], while this method returns [5, 3]. Both are correct, because the question accepts any pair. The hash set finds the pair whose later element comes first in the array.
6The complete Java program
Here is the whole program. findPair returns the two values as an int array, or an empty array when no pair exists. main runs the example, a case with no pair, two equal values, a single value that must not pair with itself, and negative numbers, and each comment shows what the line prints.
Let us read findPair in the order it runs. First we create an empty HashSet called seen, Java's ready-made hash set. The for loop then gives us each value x of the array in turn, from the left.
Inside the loop we first compute need = k - x, the one partner that would work. Then seen.contains(need) asks the set whether that partner appeared earlier. If it did, we return new int[] {need, x}, with need first because it came earlier. If not, seen.add(x) records x for the elements still to come. This line comes after the check, which is what keeps x from pairing with itself.
If the loop finishes without returning, no pair exists, and we return new int[0], an empty array.
In main, [1, 2, 3] with 7 prints [], because the needed partners, 6, 5 and 4, never appear. [5, 5] with 10 prints [5, 5], and [5] with 10 prints [], which shows the check-before-add rule working both ways. [-3, 4, 10] with 7 prints [-3, 10]: -3 needs 10 and is added, 4 needs 3, and 10 needs -3, which is in the set. Negative numbers need nothing special.
7How much it costs, and the cases at the edges
Let us count on the example first. We read five values, and for each we did one subtraction, one lookup and at most one insertion, about fifteen simple steps, against nine pair checks for the brute force on this lucky example and 15 if no pair existed. For n elements the loop runs at most n times with O(1) work each on average, so the time is O(n). The set may end up holding every element, so the extra space is O(n).
This is the trade at the heart of hashing, spending memory to save time. The table puts the three approaches side by side, including sorting with two pointers, which spends time to save memory.
| Approach | Time | Extra space | Keeps original order? |
|---|---|---|---|
| Check every pair | O(n^2) | O(1) | yes |
| Sort, then two pointers | O(n log n) | O(1) if sorting in place | no |
| One pass with a hash set | O(n) | O(n) | yes |
The edge cases need no special code. An empty array or a single element returns an empty array, because no partner can be in the set when it is checked. Equal values work because the first copy is in the set when the second arrives. Negative numbers and zero need nothing special. If several pairs exist, we return the one whose later element comes first.
One rare trap is overflow. If the values can be near the limits of int, k - x can pass the largest int and wrap round to a wrong value. In that case we compute need as a long and keep a set of Long values.
8Follow-up questions
What if we must return the positions, as in the classic two sum?
We use a HashMap from value to position instead of a set. For each index i, we look up K - a[i] in the map; if it is there, we return the stored position and i, and if not, we put a[i] with its position i. Everything else stays the same, including checking before adding. Sorting with two pointers is awkward here, because sorting moves the values away from their original positions.
How would you count all the pairs that add up to K?
We use a HashMap from value to how many times we have seen it so far. For each x, every earlier copy of K - x forms a new pair with x, so we add the count of K - x to the total, and then increase the count of x. Each pair of positions is counted exactly once, when we reach its later element, and the time is still O(n).
What if the array is already sorted, or memory is tight?
Then two pointers is the better answer. We put left on the first element and right on the last. If their sum is too small, only moving left forwards can increase it; if it is too large, only moving right backwards can decrease it; if it equals K, we return the pair. On a sorted array that is O(n) time and O(1) space. On an unsorted array we sort first, which makes it O(n log n) time.
9Conclusion
We found two elements that add up to K by walking the array once with a hash set. Each value x has exactly one possible partner, K - x, so we check whether that partner has already been seen, return the pair if it has, and otherwise remember x. Checking before adding keeps an element from pairing with itself. That is O(n) time and O(n) space, against O(n^2) for every pair. The clue to remember is that each element tells us exactly which value it needs: then a hash lookup replaces the inner loop.
Open with
Let me confirm the details: the array is unsorted, may hold negatives and duplicates, I return the two values, any valid pair is fine, and I return an empty array if there is none.
Then, if they want more
The brute force checks every pair with two loops, which is n squared. But once I fix one element x, its partner must be exactly k minus x, so the inner loop is really a search for one known value, and that is what a hash set does in constant time on average. So I walk the array once.
For each x I compute need as k minus x and check whether need is in the set. If it is, I return need and x. If not, I add x and continue. Checking before adding means an element never pairs with itself, so a single five with target ten returns nothing, while two fives return the pair.
Every pair is found when I reach its later element, because the earlier one is already in the set. That is O(n) time and O(n) space. If memory mattered more, I would sort and use two pointers, n log n time and constant space, and for positions I would use a HashMap from value to index.
About this answer
- Last updated
- 14 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 19 times in that collection. How it is counted
- Official documentation
- HashSet (Java 21), Arrays (Java 21), java.util, package documentation
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 "Determine whether an array has two elements whose sum is K, and return them.": https://scrivio-interview-library.netlify.app/data-structures/solutions/determine-whether-an-array-has-two-elements-whose-sum-is-k-and-r-759017/