1. Two Sum
easy
arrays-hashing
Find two numbers that add up to target.
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Approach
Use a hash map to store complements. For each element, check if its complement exists in the map — O(n) time, O(n) space.
Solutions
Ruby
def two_sum(nums, target)
seen = {}
nums.each_with_index do |num, i|
complement = target - num
return [seen[complement], i] if seen.key?(complement)
seen[num] = i
end
end
Python
def two_sum(nums: list[int], target: int) -> list[int]:
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
Go
func twoSum(nums []int, target int) []int {
seen := make(map[int]int)
for i, num := range nums {
complement := target - num
if j, ok := seen[complement]; ok {
return []int{j, i}
}
seen[num] = i
}
return nil
}
TypeScript
function twoSum(nums: number[], target: number): number[] {
const seen = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (seen.has(complement)) {
return [seen.get(complement)!, i];
}
seen.set(nums[i], i);
}
return [];
}
Elixir
defmodule Solution do
def two_sum(nums, target) do
nums
|> Enum.with_index()
|> Enum.reduce_while({%{}, nil}, fn {num, i}, {seen, _} ->
complement = target - num
case Map.get(seen, complement) do
nil -> {:cont, {Map.put(seen, num, i), nil}}
j -> {:halt, {seen, [j, i]}}
end
end)
|> elem(1)
end
end