twoSum
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. You can return the answer in any order.
Examples
twoSum([2, 7, 11, 15], 9) → [0, 1]
twoSum([3, 2, 4], 6) → [1, 2]
twoSum([3, 3], 6) → [0, 1]
Starter code
function twoSum(nums, target) {
}
Complexity of the optimal solution
Time O(n), space O(n). This solution iterates through the array once. For each element, it performs a constant time lookup in the hash map (`Map`). This results in a linear time complexity. The map can store up to n elements in the worst case, so space is also O(n).