Two Sum Challenge
Find two numbers in an array that add up to a target value. Learn hash map techniques and array manipulation.
Target Sum
Array:
šÆ Problem Statement
Given an array of integers and a target sum, find two numbers in the array that add up to the target. Return the indices of these two numbers. You may assume that each input has exactly one solution, and you may not use the same element twice.
š” Key Concepts
Hash Map Approach
Use a hash map to store numbers we have seen and their indices. For each number, check if its complement (target - number) exists.
One Pass Solution
We can solve this in a single pass through the array, making it O(n) time complexity.
š Algorithm Pseudo Code
function twoSum(nums, target):
// Create a hash map to store numbers and their indices
hashMap = {}
// Iterate through the array once
for i from 0 to length(nums) - 1:
// Calculate the complement we need
complement = target - nums[i]
// Check if complement exists in hash map
if complement in hashMap:
// Found the pair!
return [hashMap[complement], i]
// Store current number and its index
hashMap[nums[i]] = i
// No solution found (should not happen given problem constraints)
return []š Step-by-Step Example
Input: nums = [2, 7, 11, 15], target = 9
Step 1: i=0, nums[0]=2, complement=9-2=7
hashMap = {2: 0}
Step 2: i=1, nums[1]=7, complement=9-7=2
Found 2 in hashMap! Return [0, 1]
Result: [0, 1] because nums[0] + nums[1] = 2 + 7 = 9
š Hash Map Visualization
ā±ļø Complexity Analysis
Time Complexity
O(n) - Single pass through the array
Space Complexity
O(n) - Hash map storage
š Alternative Approaches
Brute Force
O(n²) - Check all pairs
Hash Map (Optimal)
O(n) - Single pass with hash map
š Real-world Applications
1. Click on two numbers in the array
2. Their sum should equal the target value
3. You cannot use the same element twice
4. Find the correct pair to advance
5. Complete all levels to win!