Two Sum
Finds two indices in an array whose values sum to a target
Problem Overview
- The Classic Two Sum Challenge
🔍 Problem Breakdown:
- Given:
[2, 7, 11, 15]and target9 - Find: Indices where numbers sum to target
- Return:
[0, 1](because2 + 7 = 9) - Two Solution Strategies:
- Brute Force: Check every pair → O(n²) time, O(1) space
- Hash Map: Single pass with lookups → O(n) time, O(n) space
- Time vs Space complexity trade-offs
- Hash table optimization patterns
- Array indexing and iteration strategies
- Interview problem-solving methodology
- Why This Matters:
- Foundation for more complex sum problems (3Sum, 4Sum)
- Demonstrates hash map optimization techniques
- Tests ability to recognize algorithmic improvements
- Common technical interview screening question
Concepts
array iterationhash mapsbrute-force
Complexity Analysis
Time:O(n) for hash map, O(n²) for brute-force
Space:O(n) for hash map, O(1) for brute-force
Solutions
twoSum
Time: O(n) | Space: O(n)
export function twoSum(nums: number[], target: number): number[] {
if (!Array.isArray(nums) || nums.length < 2) throw new Error("Input must be an array with at least two numbers");
const numToIndex: { [key: number]: number } = {};
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (numToIndex[complement] !== undefined) return [numToIndex[complement], i];
numToIndex[nums[i]] = i;
}
throw new Error("No two numbers sum to the target");
}Examples & Test Cases
#1Basic
Input:
[
[
2,
7,
11,
15
],
9
]Output:
[
0,
1
]#2Not at start
Input:
[
[
3,
2,
4
],
6
]Output:
[
1,
2
]#3Duplicates
Input:
[
[
3,
3
],
6
]Output:
[
0,
1
]#4No solution
Input:
[
[
1,
2,
3
],
10
]Output:
{}#5Too short
Input:
[
[
1
],
2
]Output:
{}#6Invalid
Input:
[
null,
5
]Output:
{}