1. Two Sum ๐
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Easy
- Tags: Array
, Hash Table
Given an array of integers nums
and an integer target
, return the 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.
๐น Example 1:
Input:
Output:
Explanation: nums[0] + nums[1] == 9
, so we return [0, 1]
.
๐น Example 2:
Input:
Output:
๐น Example 3:
Input:
Output:
2 <= nums.length <= 10^4
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
Only one valid answer exists.
We can use a HashMap
to store the difference between the target
and each element as we iterate through the array.
Initialization:
Create a HashMap
to store the value and its index as key-value pairs.
Traversal:
For each element in nums
, calculate the complement (target - nums[i]
).
Check if the complement exists in the HashMap
.
If it does, return the current index and the stored index for the complement.
Otherwise, add the current element and its index to the HashMap
.
Result:
Return the indices of the two numbers when the complement is found.
O(n):
Each lookup and insertion in the HashMap
takes constant time.
O(n):
Space used by the HashMap
to store up to n
elements.
You can find the full solution .