Question – Two Sum Problem
Given an array of integer numbers and an integer target, return indices of the two numbers such that they add up to the 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.
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?
Answer:
Here’s a detailed explanation of how to implement the solution for the “Two Sum” problem using Java, including the code and a breakdown of the steps involved.
Java Code Implementation:
import java.util.HashMap;
class Solution {
public int[] twoSum(int[] nums, int target) {
// Create a HashMap to store numbers and their indices
HashMap<Integer, Integer> map = new HashMap<>();
// Iterate through the array
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i]; // Calculate the complement
// Check if the complement exists in the map
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i }; // Return indices if found
}
// Add the current number and its index to the map
map.put(nums[i], i);
}
// Throw an exception if no solution is found (though the problem guarantees a solution)
throw new IllegalArgumentException("No two sum solution");
}
}
Step-by-Step Explanation:
1. Understanding the HashMap Usage:
- We use a
HashMapto store each number and its index as we traverse through the array. - The key is the number from the array, and the value is its index.
- For each number in the array, we check if the “complement” (i.e.,
target - current number) already exists in theHashMap. If it does, that means we’ve found the two numbers that sum up to the target, and we return their indices.
2. findTwoSum Method:
- Input: An integer array
numsand an integertarget. - Output: An integer array containing the two indices of the numbers whose sum is equal to the target.
Logic:
- We first initialize a
HashMap<Integer, Integer>calledmap. This will store numbers as keys and their indices as values. - We iterate through the array using a for loop:
- For each number at the index
i, we calculate the “complement,” which istarget - nums[i]. - We check if this complement is already present in the
map. If it is, it means we have already seen a number that, when added to the current number, equals the target. - If the complement is found in the map, we return an array of two indices: the index of the complement (retrieved from the map) and the current index
i. - If the complement is not found, we add the current number along with its index to the map for future reference.
- For each number at the index
- If no solution is found (though we are guaranteed one solution per the problem constraints), we throw an exception. This is just a safety check.
3. HashMap Operations:
containsKey(complement): This checks whether theHashMapalready contains the complement number (i.e.,target - current number). This operation is efficient and has an average time complexity of O(1).put(nums[i], i): If the complement is not found, we store the current number and its index in theHashMap. This operation also runs in constant time O(1).
4. main Method:
- The
mainmethod contains test cases to verify the function:nums1 = {2, 7, 11, 15}withtarget = 9: The function finds the numbers2and7, and their indices are0and1, so it prints “Indices: 0, 1”.nums2 = {3, 2, 4}withtarget = 6: The function finds the numbers2and4, and their indices are1and2, so it prints “Indices: 1, 2”.nums3 = {3, 3}withtarget = 6: The function finds two numbers3(both at index0and1), so it prints “Indices: 0, 1”.
Time and Space Complexity:
Time Complexity: O(n)
- We iterate over the array once, and for each element, we perform a constant-time operation (i.e., checking for the complement and adding the element to the map).
- Thus, the overall time complexity is O(n), where
nis the number of elements in the array.
Space Complexity: O(n)
- In the worst case, we store all
nnumbers in theHashMap, leading to a space complexity of O(n).
Key Points:
- Efficient Lookup: The
HashMapallows for fast lookups of previously seen numbers in constant time, making this approach much more efficient than a brute-force solution. - Handling Edge Cases:
- Duplicate Numbers: The map handles duplicates well. For example, if the input is
nums = [3, 3]withtarget = 6, the solution correctly returns the indices[0, 1]. - Negative Numbers: The algorithm works for negative numbers as well, since subtraction and map lookups work just the same for negative values.
- Duplicate Numbers: The map handles duplicates well. For example, if the input is
- Guaranteed Solution: The problem guarantees exactly one solution, so we do not need to worry about cases where no solution exists.
This is an optimal and efficient solution for the Two Sum problem in terms of both time and space complexity.



Leave a comment