Find two elements in an array that sum to k
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
The “two sum” problem asks whether any two elements in an array add up to a target k, and often also asks you to return the pair or their indices. The brute-force solution is easy to write, but the standard efficient solution uses a hash set or hash map and runs in linear time on average. The right version depends on whether you need values, indices, or all matching pairs.
Brute Force Baseline
The simplest solution checks every pair.
This works, but it is O(n^2), which becomes expensive as the array grows.
Standard Efficient Solution with a Hash Map
If you need indices, store seen values and their indices as you scan left to right.
This is the usual interview-quality answer: O(n) average time and O(n) extra space.
Why the Hash Map Order Matters
The lookup must happen before storing the current value if you want to avoid using the same element twice incorrectly.
For example:
This works because the first 3 is stored, then the second 3 sees that it needs another 3 and finds the earlier index.
If you structure the logic carelessly, duplicate handling becomes buggy.
Return Values Instead of Indices
If the task asks for the two values rather than their positions, a set can be enough.
This is slightly simpler because you do not need to preserve indices.
Sorted Array Variant
If the array is already sorted, a two-pointer solution is often cleaner.
This runs in O(n) time and O(1) extra space, but it depends on sorted input.
If You Need All Pairs
Returning one match is simpler than returning every valid pair. If you need all distinct pairs, define clearly whether duplicates in the input should create duplicate outputs.
For example:
This returns unique value pairs, not every index-level combination.
Edge Cases
You should think about:
- duplicate values
- negative numbers
- zero
- no solution
- whether using the same element twice is forbidden
The standard formulation requires two distinct elements, so one array element cannot satisfy the target by pairing with itself unless it appears at least twice.
Space-Time Tradeoff
The two common efficient strategies are:
- hash map:
O(n)time,O(n)space - sorting plus two pointers:
O(n log n)time if sorting is needed,O(1)extra space on top of the array
If the input is unsorted and you need original indices, the hash-map solution is usually the best fit.
Common Pitfalls
The biggest mistake is forgetting that the two elements must usually be distinct positions, not just values. Another is mishandling duplicates such as [3, 3] for target 6. Developers also often choose the sorted two-pointer approach without realizing it destroys original index positions unless they preserve them separately. Finally, if the problem asks for all pairs, reusing the one-pair hash-map solution without clarifying duplicate semantics usually leads to ambiguous output.
Summary
- The brute-force solution checks all pairs and costs
O(n^2). - The standard efficient solution uses a hash map and runs in
O(n)average time. - Use a set if you only need matching values, not indices.
- Use two pointers when the input is already sorted.
- Be explicit about duplicate handling and whether you need one pair or all pairs.
Related reading
- Find whether a minimum spanning tree contains an edge in linear time?
- Find whether two triangles intersect or not
- Find XOR of all numbers in a given range
- Finding 2 equal sum sub-sequences, with maximum sum?
- Find unique rows in numpy.array
- Finding a corresponding leaf node for each data point in a decision tree scikit-learn
- Finding a minimal subarray of n integers of sum k in linear time
- Finding a minimum bounding sphere for a frustum

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.