How to Solve the Two Sum Challenge on LeetCode
🧩 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.
Comments
Post a Comment