
1. Two Sum - Brute Force to Optimal
- Aditya Dhawle
- Dsa , Leetcode
- May 2, 2025
Table of Contents
๐ง Problem Statement
Given an array of integers
nums
and an integertarget
, return indices of the two numbers such that they add up to the target.You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
๐งช Example
Input: nums = [2, 7, 11, 15], target = 9 Output: [0, 1] Explanation: nums[0] + nums[1] = 2 + 7 = 9
โ Brute Force Approach
๐ Idea:
Try every possible pair and check if their sum is equal to the target.
๐งพ Steps:
- Loop over each element
i
. - For every
i
, loop over the remaining elementsj > i
. - If
nums[i] + nums[j] == target
, return the indices.
๐งฎ Time Complexity:
- O(nยฒ) โ because of the nested loops
โ Code (Java):
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[]{-1, -1}; // fallback
}
โก Better Approach (Using HashMap)
๐ Idea:
Instead of checking every pair, we use a HashMap to store visited elements and their indices.
While iterating, check if target - nums[i] exists in the map.
๐งพ Steps:
Create an empty HashMap<Integer, Integer> to store value โ index.
For each element nums[i], calculate complement = target - nums[i].
If complement exists in map โ we found the pair.
Otherwise, store nums[i] โ i in the map.
โฑ Time Complexity:
O(n) โ Single pass through array
โ Code (Java):
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
map.put(nums[i], i);
}
return new int[]{-1, -1}; // fallback
}
๐ Optimal Solution: Explanation in Plain English
Letโs say the array is [2, 7, 11, 15] and the target is 9.
Start at index 0 โ value is 2 โ we want 7 (because 9-2=7).
Is 7 in the map? No. So store 2:0 in the map.
Move to index 1 โ value is 7 โ 9-7 = 2.
Is 2 in the map? Yes! We found our answer โ [0, 1].
โ๏ธ Conclusion
Brute force is good to start understanding the problem.
HashMap-based approach is the go-to optimal solution in interviews.
Always look for ways to store useful info during iteration.