1. Two Sum ๐
Difficulty: Easy
- Tags: Array
, Hash Table
Problem Statement ๐
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.
Examples ๐
๐น Example 1:
Input:
Output:
Explanation: nums[0] + nums[1] == 9
, so we return [0, 1]
.
๐น Example 2:
Input:
Output:
๐น Example 3:
Input:
Output:
Constraints โ๏ธ
2 <= nums.length <= 10^4
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
Only one valid answer exists.
Solution ๐ก
We can use a HashMap
to store the difference between the target
and each element as we iterate through the array.
Java Solution
Explanation of the Solution
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.
Time Complexity โณ
O(n):
Each lookup and insertion in the
HashMap
takes constant time.
Space Complexity ๐พ
O(n):
Space used by the
HashMap
to store up ton
elements.
You can find the full solution here.
Last updated