GitHub
Easy

Two Sum

Given an array of integers and a target sum, find the indices of two numbers that add up to the target.

Write a function that takes an array of integers and a target sum, and returns the indices of two numbers that add up to the target. You may assume that each input has exactly one solution, and you may not use the same element twice.

How to Solve

Use a hash map to store each number and its index as you iterate. For each number, check if the complement (target - current number) exists in the map. If found, return the indices. This allows you to solve it in a single pass.

Code

Test Cases

Input 1

Expected Output: [0, 1] (because nums[0] + nums[1] = 2 + 7 = 9)

Input 2

Expected Output: [1, 2] (because nums[1] + nums[2] = 2 + 4 = 6)

Input 3

Expected Output: [0, 1] (because nums[0] + nums[1] = 3 + 3 = 6)

Complexity

Time Complexity: O(n) - Single pass through the array where n is the length of the array.

Space Complexity: O(n) - Hash map stores at most n elements in the worst case.