How to Solve the Two Sum Challenge on LeetCode

Table of contents
- ๐งฉ Two Sum โ Explained simply
- ๐ Difficulty: Easy | ๐ผ Asked in Many Interviews
- ๐ The Problem (from LeetCode)
- ๐ก Letโs Understand With an Example:
- ๐ Real-Life Analogy:
- โ Common Misunderstanding
- ๐ง Solution 1: Brute Force (Beginner Friendly)
- ๐ป PHP Code
- โ Java Code
- ๐ Python Code
- ๐ JavaScript Code
- ๐ก Solution 2: Optimized Using Hash Map (For Faster Performance)
- โ Summary
- ๐ Final Tips
๐งฉ Two Sum โ Explained simply
๐ Difficulty: Easy | ๐ผ Asked in Many Interviews
๐ The Problem (from LeetCode)
Given an array of integers
nums
and an integertarget
, return the indices of the two numbers such that they add up totarget
.
You must:
Return exactly one solution (you can assume there is always one)
Not use the same element twice
Return the indexes (positions) of the numbers, not the numbers themselves
The order of the result doesnโt matter
๐ก Letโs Understand With an Example:
nums = [2, 7, 11, 15]
target = 9
We need to find two numbers from the array whose sum is 9
.
Letโs try:
- 2 + 7 = โ 9 โ Found at index 0 and 1
Answer: [0, 1]
๐ Real-Life Analogy:
Imagine you're shopping. Your friend gives you โน9 and a list of item prices. You need to pick 2 items that exactly total โน9.
Item prices = [2, 7, 11, 15]
You pick โน2 (item at index 0) and โน7 (index 1). Thatโs the answer โ [0, 1]
.
โ Common Misunderstanding
Some people only check each element and the next one (i
and i+1
). But what if the answer is in some other pair (like index 1 and 3)? That logic will miss some valid answers.
We need to try every pair, not just adjacent ones.
๐ง Solution 1: Brute Force (Beginner Friendly)
Try every possible pair of numbers. If their sum is the target, return their indexes.
๐งฎ Logic:
Loop over each number with index
i
Inside that loop, loop over every number after
i
(indexj
)Check if
nums[i] + nums[j] == target
If yes, return
[i, j]
๐ Time Complexity:
O(n^2)
(nested loops)๐ง Pseudocode:
Loop i from 0 to length-1 Loop j from i+1 to length if nums[i] + nums[j] == target return [i, j]
๐ป PHP Code
class Solution {
function twoSum($nums, $target) {
$n = count($nums); // Get the size of the array
for ($i = 0; $i < $n; $i++) {
for ($j = $i + 1; $j < $n; $j++) {
// Check if this pair sums up to the target
if ($nums[$i] + $nums[$j] == $target) {
return [$i, $j]; // Return their positions
}
}
}
return []; // Return empty if no pair found
}
}
โ Java Code
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (nums[i] + nums[j] == target) {
return new int[] { i, j };
}
}
}
return new int[] {};
}
}
๐ Python Code
class Solution:
def twoSum(self, nums, target):
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
return [i, j]
return []
๐ JavaScript Code
function twoSum(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
return [];
}
๐ก Solution 2: Optimized Using Hash Map (For Faster Performance)
Instead of checking every pair, we can:
Use a hash map to remember numbers weโve already seen
For each number, check if
target - current number
already exists in the map
โ Time: O(n), Space: O(n)
Python (Optimized):
class Solution:
def twoSum(self, nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
โ Summary
Approach | Time Complexity | Space | Easy to Understand |
Brute Force | O(nยฒ) | O(1) | โ |
Hash Map | O(n) | O(n) | โ (slightly tricky) |
๐ Final Tips
Master brute force first โ it's simple and helps understand the problem.
Later, try to learn the hash map method โ it's fast and often asked in interviews.
Practice writing in multiple languages (like we just did!) โ great for polyglot devs.
Subscribe to my newsletter
Read articles from Nature directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
