← Back to LeetCode Series

LeetCode #1: Two Sum

Solving the classic Two Sum problem using a hash map for O(n) efficiency.

5 min readJavaScript / Algorithms

Problem: Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.

You may assume that each input has exactly one solution, and you cannot use the same element twice.

The Two Sum problem asks us to find two numbers in an array that add up to a specific target.

Try It: Find Two Sum

Array: [2, 7, 11, 15], Target: 9

Brute Force Approach

Loop through every pair of numbers and check if their sum equals the target.

How? Use two nested loops:
Outer loop: pick the first number
Inner loop: try all later numbers to see if they sum to target

js
1
2
3
4
5
6
7
8
9
function twoSum(nums, target){
    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] === target) {
                return [i, j];
            }
        }
    }
}

Problems

1. Time Complexity: O(n²)

2. Space Complexity: O(1)

3. Simple to understand

4. Slow on large arrays

Optimized: Hash Map

Use a JavaScript object to store seen values and their indices.

js
1
2
3
4
5
6
7
8
9
10
11
function twoSum(nums, target) {
  const map = {};
  for (let i = 0; i < nums.length; i++) {
    const complement = target - nums[i];
    if (complement in map) {
      return [map[complement], i]; // Found a pair!
    }
    map[nums[i]] = i; // Store current number and index
  }
    return []; // in case no solution
}
💡 Tip: This pattern (hashMaps) appears in many array problems.

Real-World Example

js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function findItemsForBudget(prices: number[], budget: number): [number, number] | null {
        const seen = new Map<number, number>(); // price → index

        for (let i = 0; i < prices.length; i++) {
            const price = prices[i];
            const complement = budget - price;

            if (seen.has(complement)) {
            return [seen.get(complement)!, i];
            }

            seen.set(price, i);
        }

    return null;
}

// Example: $7.99 + $2.01 = $10.00
findItemsForBudget([5.99, 7.99, 2.01, 3.50], 10.00); // → [1, 2]

Real-World Applications of Two Sum

Two Sum seems like just a clever interview puzzle; but it‘s actually a simplified version of a powerful algorithmic pattern used across software engineering.

E-Commerce: "Find Two Items That Add Up to My Budget"

Imagine a "Shop with Budget" feature where a user says: "Show me two items that cost exactly $50". You’d use the hash map technique from Two Sum to find pairs fast even in a catalog of 10,000 products.

Fraud Detection: Matching Suspicious Transactions

If two transactions sum to a known suspicious amount (e.g., $947.32), systems can flag them. Using a hash map to track recent transaction amounts allows real-time detectionjust like checking for a complement in Two Sum.

Networking: Matching Request-Response Pairs

In network monitoring, you might want to find two packets whose timestamps add up to a specific value (e.g., round-trip time analysis). The Two Sum pattern helps match such events efficiently.

Data Analysis: Finding Complementary Values

In bio-informatics, finance, or AI, you often need to find pairs of values that sum to a target like gene expression levels, stock deltas, or sensor readings. The hash map strategy is a go-to tool for these O(n) lookups.

💡 Fun Fact: The "Two Sum" pattern is the foundation of more advanced problems like3Sum, 4Sum, and K-Sum, which are used in computational geometry and optimization algorithms.

Why It Matters: This problem teaches the powerful idea of"trading space for time" using a hash map to turn a slow O(n²) search into a fast O(n) one. That trade-off is used in caching, indexing, and almost every high-performance system.