If you're looking for a solution to the Two Sum problem in Java that has a time complexity of O(n) (which is already provided in the previous examples using a HashMap), here’s a summary focusing on the specific O(n) requirement and an explanation of how it operates, along with the complete implementation.
Two Sum Problem in O(n) with Java
The O(n) time complexity means that the algorithm will complete in linear time, which is achieved using a single pass-through of the input array combined with a HashMap to store previously seen numbers.
Complete Java Implementation
Here is the Java code for the Two Sum problem using an O(n) approach:
import java.util.HashMap;
public class TwoSum {
public static int[] twoSum(int[] nums, int target) {
// Create a HashMap to map numbers to their indices
HashMap<Integer, Integer> numToIndex = new HashMap<>();
// Loop through the array once
for (int index = 0; index < nums.length; index++) {
// Calculate the complement of the current number
int complement = target - nums[index];
// Check if the complement exists in the HashMap
if (numToIndex.containsKey(complement)) {
// If found, return the indices of the numbers
return new int[] { numToIndex.get(complement), index };
}
// Otherwise, add the current number and its index to the HashMap
numToIndex.put(nums[index], index);
}
// If no solution is found, return an empty array or null
return null; // or throw new IllegalArgumentException("No two sum solution found");
}
public static void main(String[] args) {
// Test example
int[] nums = {2, 7, 11, 15};
int target = 9;
int[] result = twoSum(nums, target);
if (result != null) {
System.out.println("Indices: " + result[0] + ", " + result[1]);
} else {
System.out.println("No two sum solution.");
}
}
}
How It Works
-
HashMap Initialization: The HashMap<Integer, Integer> numToIndex is created to store integer values from the nums array as keys and their corresponding indices as values.
-
Single Loop: We iterate through the nums array just once. This ensures that our overall time complexity remains O(n).
-
Calculate the Complement: For each element, calculate its complement by subtracting the current element from the target.
-
Check for Existing Complement: Use numToIndex.containsKey(complement) to check if the complement has been seen before (i.e., if it exists in the HashMap). If it exists, the problem is solved, and we return the indices.
-
Store Current Element: If the complement does not exist, the current number and its index are inserted into the HashMap.
-
Final Check: If no valid pairs are found that sum to the target, it returns null.
Space Complexity
The space complexity is O(n) because we could potentially store every element of the input in the HashMap.
Usage
You can run the main method to see how the solution works with the example {2, 7, 11, 15} and target 9. The console should output Indices: 0, 1 as nums[0] + nums[1] == 9.
This implementation effectively meets the O(n) complexity requirement for solving the Two Sum problem using a HashMap!