Share with me your thought process on implementing the two sum problem using a hash table in O(n) time complexity.
Question Analysis
The "Two Sum" problem is a classic coding interview question where you are given an array of integers and a target sum. Your task is to find two numbers in the array that add up to the target sum and return their indices. The challenge lies in doing this efficiently, ideally in O(n) time complexity, where n is the number of elements in the array.
Using a hash table (or hash map) is a common approach to solve this problem efficiently. A hash table allows for average O(1) time complexity for both insert and lookup operations. The key idea is to leverage the hash table to store the numbers you have seen so far and quickly check if the complement (i.e., target - current_number
) exists in the hash table.
Answer
To implement the Two Sum problem using a hash table in O(n) time complexity, follow these steps:
-
Initialize a Hash Table: Create an empty hash table to store numbers and their respective indices as you iterate through the array.
-
Iterate Through the Array: Loop through each element in the array. For each element, calculate the complement (i.e.,
target - current_number
). -
Check for Complement: Before inserting the current number into the hash table, check if the complement exists in the hash table:
- If it does, you have found the two numbers that add up to the target; return their indices.
- If it doesn't, add the current number and its index to the hash table.
-
Return the Result: If you find the complement during iteration, you can immediately return the indices of the two numbers.
Here is a sample implementation in Python:
def two_sum(nums, target):
# Step 1: Initialize the hash table
hash_table = {}
# Step 2: Iterate through the array
for index, num in enumerate(nums):
# Step 3: Calculate the complement
complement = target - num
# Step 4: Check for complement in the hash table
if complement in hash_table:
# If found, return the indices
return [hash_table[complement], index]
# If not found, add the current number and its index to the hash table
hash_table[num] = index
# If no solution found, return an empty list or appropriate message
return []
# Example usage:
# nums = [2, 7, 11, 15]
# target = 9
# print(two_sum(nums, target)) # Output: [0, 1]
Key Points:
- Efficiency: This approach efficiently finds the solution in O(n) time complexity due to the hash table's average O(1) operations.
- Space Complexity: The space complexity is O(n) as well, as we store each element in the hash table.
- Edge Cases: Consider edge cases such as arrays with duplicate numbers or no valid pairs, and adjust the implementation as needed.