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.

Constraints

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • Only one valid answer exists.

Example

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Solution

Approach: Using a Hash Map (Dictionary)

This problem can be efficiently solved using a hash map (also known as a dictionary or hash table) to store numbers and their indices.

  • Iterate through the nums array, keeping track of both the current element's value and its index.
  • For each number num at index i, calculate the complement needed to reach the target: complement = target - num.
  • Check if this complement already exists as a key in our hash map:
    • If it does, it means we've found the other number that sums up to the target. We return the index of the complement (stored in the map) and the current index i.
    • If it does not, add the current num and its index i to the hash map (e.g., map[num] = i) for future lookups.
  • This approach ensures an average time complexity of O(n) because hash map lookups and insertions typically take O(1) time.

Code (Python)

def twoSum(nums, target):
    # Create a hash map to store numbers and their indices (value -> index)
    num_map = {}
    
    # Iterate through the array with index and value
    for i, num in enumerate(nums):
        complement = target - num
        
        # Check if the complement exists in the map
        if complement in num_map:
            # If found, return its index and the current index
            return [num_map[complement], i]
        
        # If not found, add the current number and its index to the map
        num_map[num] = i
    
    # According to the problem statement, there will always be exactly one solution,
    # so this part should ideally not be reached.
    return []