šŸŽÆ

Two Sum Challenge

Beginner

Find two numbers in an array that add up to a target value. Learn hash map techniques and array manipulation.

15-20 min
Level 1 - Easy
Score: 0Attempts: 0

Target Sum

9

Array:

Two Sum - Hash Map Algorithm

šŸŽÆ 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

Example: [2, 7, 11, 15], target = 9
i=0:nums[0]=2, complement=7hashMap = {2: 0}
i=1:nums[1]=7, complement=2Found 2! Return [0, 1]

ā±ļø 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

šŸ’°Financial calculations
šŸŽÆTarget matching
šŸ”Data analysis
āš–ļøBalance checking
Progress1 / 6
Algorithm:Two Sum
šŸŽÆ How to Play

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!

šŸ“Š Difficulty Levels
Easy: Small arrays, simple targets
Medium: Larger arrays, hash map needed
Hard: Large arrays, optimal solution required