1. Two Sum
Intuition
The problem requires finding two numbers in an array that add up to a target value. A straightforward approach would be using two nested loops to check every possible pair, but that would be inefficient. Instead, we can use a hash map to store previously seen numbers and their indices, which allows us to find complements in constant time.
Approach
- Create a hash map to store numbers and their indices
- Iterate through the array once
- For each number:
- Calculate the complement (target - current number)
- Check if the complement exists in the hash map
- If found, return current index and the complement's index
- If not found, store current number and its index in the hash map
- Continue until a solution is found
Complexity
- Time complexity: O(n)
- Space complexity: O(n)
Keywords
- Hash Map