LeetCode Problem: Two Sum
Difficulty: Easy
Topics: Array, Hash Table
Series: LeetCode Interview Preparation — From Beginner to Expert
If you are preparing for a software engineering interview, there is a good chance you will encounter a problem similar to Two Sum.
It looks extremely simple:
Given an array of integers and a target value, find two numbers whose sum equals the target.
But Two Sum teaches one of the most important skills in coding interviews:
How to take a brute-force solution and optimize it using the right data structure.
This makes it the perfect starting point for our Kairos Coders LeetCode Interview Preparation Series.
You are given an integer array nums and an integer target.
Find the indices of two numbers such that:
nums[i] + nums[j] = targetYou may assume that:
Input:
nums = [2, 7, 11, 15]
target = 9
Output:
[0, 1]Why?
nums[0] + nums[1]
= 2 + 7
= 9Therefore, the answer is:
[0, 1]The most obvious solution is to check every possible pair.
For every element:
For:
[2, 7, 11, 15]we would check:
2 + 7 = 9 ✓
2 + 11 = 13
2 + 15 = 17
7 + 11 = 18
7 + 15 = 22
11 + 15 = 26We eventually find the answer.
def twoSum(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return []This solution is correct.
But can we do better?
Absolutely.
The problem is the nested loop.
For every element, we potentially check every other element.
If the array contains n elements, the number of comparisons can approach:
n × nTherefore:
O(n²)O(1)For a small array, this is fine.
But imagine:
n = 100,000Checking potentially billions of combinations is clearly inefficient.
This is where interviewers expect you to think about data structures.
Suppose we are currently looking at:
nums[i] = 2and:
target = 9What number do we need?
Simple:
9 - 2 = 7So instead of asking:
"Which other numbers should I try?"
we can ask:
"Have I already seen the number I need?"
This changes the entire problem.
A hash map allows us to store values and quickly check whether a value already exists.
In Python, we can use a dictionary.
We'll store:
number → indexFor example:
{
2: 0,
7: 1
}Now we can check whether a required number exists in approximately constant time.
Let's walk through the example:
nums = [2, 7, 11, 15]
target = 9Initially:
seen = {}Current number:
2Calculate the number we need:
9 - 2 = 7Is 7 already in the map?
NoStore:
seen = {
2: 0
}Current number:
7Calculate:
9 - 7 = 2Is 2 already in the map?
Yes!We stored:
2 → index 0The current index is:
1Therefore:
[0, 1]is our answer.
def twoSum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []This is the solution you should understand rather than simply memorize.
Let's break it down.
seen = {}This stores numbers we have already encountered.
for i, num in enumerate(nums):For every element, we have:
i → index
num → current valueFor example:
i = 0
num = 2complement = target - numIf:
target = 9
num = 2then:
complement = 9 - 2
complement = 7So we need 7.
if complement in seen:We ask:
Have we already encountered the number we need?
If yes, we have found our pair.
return [seen[complement], i]The dictionary contains the index of the previous number.
If the complement isn't found:
seen[num] = iWe save the current number for future iterations.
Let's make the process visual.
nums = [2, 7, 11, 15]
target = 9| Index | Number | Complement | Seen Before? | Action |
|---|---|---|---|---|
| 0 | 2 | 7 | No | Store 2 → 0 |
| 1 | 7 | 2 | Yes | Return [0, 1] |
The algorithm stops immediately after finding the answer.
The fundamental equation is:
a + b = targetRearrange it:
b = target - aTherefore, for every number a, we only need to check whether:
target - ahas already appeared.
The hash map makes that lookup extremely fast.
This is the central idea behind the solution.
We iterate through the array once.
For each element, we perform hash-map operations that are O(1) on average.
Therefore:
O(n)O(n)We potentially store every element in the hash map.
This is the important interview lesson.
| Approach | Time | Space |
| Brute Force | O(n²) | O(1) |
| Hash Map | O(n) average | O(n) |
We traded some memory for a significant improvement in execution time.
This is one of the most common optimization techniques in programming interviews.
Consider:
nums = [3]
target = 6You cannot use the same 3 twice.
That's why our algorithm checks the complement before storing the current number:
if complement in seen:
return [seen[complement], i]
seen[num] = iThis ordering matters.
The problem asks for:
[0, 1]not:
[2, 7]Always carefully read what the problem asks you to return.
You might think:
"I can sort the array and use two pointers."
That's a valid strategy for a variation of the problem, but there is an important problem here.
The question asks for original indices.
If you sort the array, you change the positions.
You would therefore need additional bookkeeping to preserve the original indices.
The hash-map solution avoids this complication.
Once you solve Two Sum, an interviewer might ask:
Yes, a brute-force approach uses O(1) extra space but takes O(n²) time.
If the interviewer insists on O(1) auxiliary space while preserving the original array, the trade-off becomes more complicated because you need to maintain index information.
If the input is already sorted, a two-pointer approach becomes possible.
Example:
[2, 7, 11, 15]Use:
left → beginning
right → endThen:
leftrightThis gives:
O(n)time and:
O(1)extra space.
Then the problem definition matters.
You might need to:
Each variation may require a different implementation.
This problem isn't really about Two Sum.
It teaches a reusable pattern:
Current Value
↓
What do I need?
↓
Target - Current Value
↓
Have I seen it before?
↓
Hash Map LookupYou will see this idea repeatedly in interview questions involving:
Once you recognize this pattern, many problems become much easier.
When you see a problem containing something like:
"Find two elements..."
or:
"Find whether two values add up to..."
or:
"Find a pair satisfying..."
Immediately ask yourself:
Can I calculate what the missing value must be?
For Two Sum:
missing = target - currentThen ask:
Can a hash map help me remember what I've already seen?
This thought process is more valuable than memorizing the code.
If the array is sorted, we can solve the problem using two pointers.
def twoSumSorted(nums, target):
left = 0
right = len(nums) - 1
while left < right:
total = nums[left] + nums[right]
if total == target:
return [left, right]
if total < target:
left += 1
else:
right -= 1
return []The idea:
↓ ↓
[2, 7, 11, 15]
L RIf:
2 + 15 = 17which is greater than:
9we move the right pointer:
2 + 11 = 13Still too large.
Move again:
2 + 7 = 9Found it.
Don't just remember:
seen = {}Remember the reasoning:
Start with the obvious brute-force solution.
Identify why it is slow.
Look for repeated work.
Ask whether a data structure can make that work faster.
Use a hash map to remember previous values.
Convert:
a + b = targetinto:
b = target - aLook up the complement in O(1) average time.
This is problem-solving, not memorization.
Before your interview, remember:
Problem:
Find two numbers whose sum equals target.
Brute Force:
Try every pair.
Brute Force:
O(n²) time
O(1) space
Optimized:
Hash Map
For every number:
complement = target - number
If complement exists:
return its index + current index
Otherwise:
store current number.
Optimized:
O(n) average time
O(n) spaceNow try solving these variations yourself:
Find whether any pair adds up to a target.
Return the number of pairs that add up to a target.
Find all unique pairs whose sum equals the target.
Solve Two Sum when the input array is already sorted.
Solve the problem using two pointers.
These variations will help you understand the underlying pattern rather than simply remembering LeetCode #1.
Two Sum is easy—but its lesson is fundamental.
A strong software engineer doesn't immediately jump into writing nested loops.
They ask:
"What information can I remember so I don't have to calculate the same thing again?"
The hash map gives us that memory.
Instead of checking every possible pair:
O(n²)we can remember what we've already seen and solve the problem in:
O(n)That transition—from brute force to optimized thinking—is exactly what technical interviews are designed to test.
And this is where our Kairos Coders LeetCode Interview Preparation Series begins.
Next: We'll move beyond Two Sum and start learning another fundamental interview pattern that appears again and again across coding interviews.
Pixels to Perfection Design that Impresses