Two Sum
🔗 NeetCode Problem:https://neetcode.io/problems/two-integer-sum/question?list=neetcode150 🔗 LeetCode Problem:
https://leetcode.com/problems/two-sum
Problem Statement
Given an array of integersnums and an integer target, return the indices of the two numbers that add up to the target.
You may assume each input has exactly one solution, and you cannot use the same element twice.
Approach 1: Brute Force (Nested Loop)
Idea
Check every pair of elements to see if they sum to the target.Pseudocode
C++ Implementation
Complexity Analysis
- Time Complexity: O(n²) → Nested loops over the array
- Space Complexity: O(1) → No extra space needed
Why it’s not optimal?
For large arrays, checking every pair becomes very slow. With 10,000 elements, we’d check ~50 million pairs in the worst case.Optimized Approach: Using Unordered Map (One Pass)
Idea
Use a hash map to store elements we’ve seen along with their indices.For each element, calculate what we need (
target - nums[i]) and check if it exists in the map.If it does, we found our pair!
Key Insight
Instead of checking all future pairs (brute force), we check if the complement already exists in previous elements.How it works:
- For each number
nums[i], calculatediff = target - nums[i] - Check if
diffexists in our hash map - If yes, return the indices (previous index and current index)
- If no, store
nums[i]with its index for future lookups
C++ Implementation
Complexity Analysis
- Time Complexity: O(n) → Single pass through the array with O(1) average-case lookups
- Space Complexity: O(n) → Hash map stores up to n elements
Why it’s optimal?
Single pass with O(1) lookups. No redundant checks. Early termination when pair is found. Complement approach is elegant and efficient.Comparison: Brute Force vs Optimized
| Approach | Time Complexity | Space Complexity | Pros | Cons |
|---|---|---|---|---|
| Brute Force | O(n²) | O(1) | No extra space | Very slow for large arrays |
| Unordered Map | O(n) | O(n) | Fastest, one pass | Uses extra memory |
Why Unordered Map is Most Optimal
- Single pass: O(n) time complexity
- O(1) lookups: Average case hash map operations
- No redundant checks: Never checks the same pair twice
- Early termination: Returns immediately when pair is found
- Elegant logic: Complement-based approach is intuitive
- Preserves indices: Returns original array indices correctly
Example Walkthroughs
Example 1: nums = [2, 7, 11, 15], target = 9
Using Unordered Map:
Example 2: nums = [3, 2, 4], target = 6
Using Unordered Map:
Example 3: nums = [3, 3], target = 6
Using Unordered Map:
Key Takeaways
- Avoid brute force for this problem (O(n²) is too slow)
- Unordered map is optimal (O(n) time, O(1) average lookups)
- Complement approach: Calculate what you need (
target - nums[i]), then look for it - Single pass is efficient: Don’t check all future pairs
- Early termination: Return as soon as the pair is found
- Hash map strength: Fast lookups make finding complements efficient