Problem Statement
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
text
1Input: nums = [2,7,11,15], target = 92Output: [0,1]3Explanation: nums[0] + nums[1] = 2 + 7 = 9Approach 1: Brute Force
The simplest approach is to check every pair of numbers.
python
1def twoSum(nums: List[int], target: int) -> List[int]:2 n = len(nums)3 for i in range(n):4 for j in range(i + 1, n):5 if nums[i] + nums[j] == target:6 return [i, j]7 return []Time Complexity: O(n²)
Space Complexity: O(1)
Approach 2: Hash Map (Optimal)
Use a hash map to store seen numbers and their indices.
python
1def twoSum(nums: List[int], target: int) -> List[int]:2 seen = {}3 for i, num in enumerate(nums):4 complement = target - num5 if complement in seen:6 return [seen[complement], i]7 seen[num] = i8 return []Time Complexity: O(n)
Space Complexity: O(n)