Two Sum
ArraysHash Table
EasyLeetCode #1
Problem Statement
Given an array of integers nums
and an integer target
, return indices of the two numbers in the array 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
3
8
11
15
2
6
0
1
2
3
4
5
11 + 15 = 17
(indices: [2, 3])
Solution Pair
Array Elements
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation:
- nums[0] + nums[1] = 2 + 7 = 9
- Therefore, we return [0,1]
Constraints
- ⢠2 ⤠nums.length ⤠10ā“
- ⢠-10⹠⤠nums[i] ⤠10ā¹
- ⢠-10⹠⤠target ⤠10ā¹
- ⢠Exactly one valid answer exists
- ⢠Same element cannot be used twice
Solution Approaches
- ⢠Brute Force: Check every pair (O(n²))
- ⢠Hash Table: Store complement values (O(n))
- ⢠Two Pointers: If array is sorted (O(n log n))
- ⢠Space-Time tradeoff possible
Algorithm Explanation
The Two Sum problem can be solved efficiently using a hash map to store complements of each number as we traverse the array. This allows us to find pairs in a single pass.
Key Steps
- Hash Map: Store each number's complement (target - num) as key with its index as value.
- Current Number: Check if the current number exists as a key in the map.
- Complement: If found, we've found a valid pair that sums to target.
- Update Map: If not found, add current number's complement to the map.
Solution Properties
- Time Complexity: O(n) - single pass through array
- Space Complexity: O(n) - hash map storage
- In-place: No modifications to input array
- Early termination: Returns as soon as pair is found
Two Sum Visualization
Target Sum: 17
3
0
8
1
11
2
15
3
2
4
6
5
Hash Map
Start: Initialize search
Looking for two numbers that sum to 17
Step 1 of 11
Current Number
Solution Pair
Array Elements
Code Example