Given an array of integers and a target, return the indices of two numbers that add up to the target.
nums = [2,7,11,15], target = 9 → [0,1]
# 🧮 1. Two Sum
# Given an array of integers and a target, return the indices of two numbers that add up to the target.
# Uses a hash map to store complements for quick lookup.
#
# Time Complexity: O(n)
# Why: One pass through nums with constant-time hash lookups.
def two_sum(nums, target)
hash = {}
nums.each_with_index do |num, i|
complement = target - num
return [ hash[complement], i ] if hash.key?(complement)
hash[num] = i
end
[] # no solution
O(n)O(n)