1. Two Sum
Description
Difficulty: Easy
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.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
- 2 <= nums.length <= 104
- -109 <= nums[i] <= 109
- -109 <= target <= 109
- Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
Solution
The algorithm iterates through the input array nums once. For each element encountered, it calculates the "complement" needed to reach the target. It then checks if this complement has been seen before (and stored in the hash map).
Initialization:
- An empty
HashMap<Integer, Integer>namedmapis initialized. This map will store elements ofnumsas keys and their corresponding indices as values.
- An empty
Iterative Search and Storage:
The algorithm iterates through the
numsarray using aforloop, withirepresenting the current index.Calculate Complement: For each
nums[i], thecomplementis calculated astarget - nums[i]. Thiscomplementis the number that, when added tonums[i], would equal thetarget.Check for Complement: The algorithm then checks if this
complementalready exists as a key in themapusingmap.containsKey(complement).If Found: If the
complementis found in the map, it means we have successfully found two numbers that sum up to thetarget. The indices aremap.get(complement)(the index of the stored complement) andi(the index of the current number). An array containing these two indices is immediately returned.If Not Found: If the
complementis not found in the map, it means the currentnums[i]is not the second part of a pair found so far. In this case,nums[i]and its current indexiare stored in the map usingmap.put(nums[i], i). This prepares the map for future iterations, wherenums[i]might be thecomplementfor a later number.
No Solution:
- If the loop completes without finding any pair that sums to the
target, an empty integer arraynew int[0]is returned. This indicates that no such pair exists in the input array.
- If the loop completes without finding any pair that sums to the
Code
import java.util.HashMap;
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
return new int[0];
}
}Time Complexity: O(n)
The algorithm iterates through the nums array exactly once.
Inside the loop, HashMap operations (containsKey and put) have an average time complexity of O(1). In the worst-case scenario (due to hash collisions), these operations could degrade to O(n), but for typical hash functions and data, the average case dominates.
Therefore, the total time complexity is linear with respect to the number of elements in the input array.
Space Complexity: O(n)
In the worst-case scenario, if no pair is found until the very last element (or no pair exists), the HashMap could end up storing all n elements from the nums array.
Each entry in the HashMap stores an integer (the number) and another integer (its index). Thus, the space required grows linearly with the number of elements in the input array.
