Two Sum
ArrayHashingTwo Pointers
Approach 1: Brute Force
The most straightforward solution is to check every pair of numbers in the array to see if they add up to the target. This is done using nested loops.
Interactive Brute Force Visualization
Step 0 of 21 ⢠Comparisons: 0 ⢠Target: 9
Array:
nums
0
3
1
2
2
4
3
7
4
8
5
11
6
15
š Checking all pairs...
Click 'Next' to start the brute force approach.
Algorithm Steps
- Iterate through the array with a pointer
i
from the first to the last element. - For each element, iterate through the rest of the array with a pointer
j
fromi + 1
to the last element. - Check if
nums[i] + nums[j]
equals thetarget
. - If it does, return the indices
[i, j]
.
Complexity Analysis
- Time Complexity: O(n²). For each element, we iterate through the rest of the array.
- Space Complexity: O(1). We are not using any extra space.
Brute Force Solution
Approach 2: Hash Map
A more efficient approach is to use a hash map to store the numbers we've seen and their indices. This allows us to find the complement of each number in constant time.
Interactive Hash Map Visualization
Step 0 of 7 ⢠Target: 9
Array:
nums
0
3
1
2
2
4
3
7
4
8
5
11
6
15
Hash Map
0 entries
Empty hash map
š Searching...
Click 'Next' to start the visualization.
Algorithm Steps
- Create an empty hash map.
- Iterate through the array with a pointer
i
. - For each element
nums[i]
, calculate thecomplement
(target - nums[i]). - Check if the
complement
exists in the hash map. - If it does, we have found our pair. Return the index of the complement from the map and the current index
i
. - If it doesn't, add the current number and its index to the hash map.
Complexity Analysis
- Time Complexity: O(n). We iterate through the array only once.
- Space Complexity: O(n). In the worst case, we store all n elements in the hash map.
Hash Map Solution