3. Two Sum
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.
Code
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for (int index = 0; index < nums.length; index++) {
for (int innerIndex = 0; innerIndex < nums.length; innerIndex++) {
if (index != innerIndex && (nums[index] + nums[innerIndex] == target)) {
result[0] = index;
result[1] = innerIndex;
return result;
}
}
}
return result;
}
}An integer array named
resultis initialized with a size of 2. This array will eventually hold the indices of the two numbers that sum to the target.The method uses a nested loop to iterate through the
numsarray:The outer loop (
index) goes through each element of the array.The inner loop (
innerIndex) also goes through the entire array.
Inside the inner loop, the code checks two conditions:
index != innerIndex: Ensures that the same element is not used twice.(nums[index] + nums[innerIndex] == target): Checks if the sum of the two elements at the current indices equals thetarget.
If a valid pair is found, the indices of these elements are stored in the
resultarray. The method then immediately returns theresultarray, exiting the method.If the loops complete without finding any valid pairs, the method returns the
resultarray, which would contain the default values (both indices as0), since it was initialized with no specific values.
The above solution when executed took 119ms of time to be executed. While this is straightforward, it has a time complexity of O(n²), where n is the length of the nums array. This means it can be inefficient for large arrays. To enhance efficiency, a more optimal solution can be achieved using a HashMap, allowing for a time complexity of O(n). The HashMap would store each number and its index, allowing the program to find the complement of the current number (i.e., target - nums[index]) in constant time.

Code: Using Hashmap
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> numberMap = new HashMap<Integer, Integer>();
for (int index = 0; index < nums.length; index++) {
int difference = target - nums[index];
if (numberMap.containsKey(difference)) {
return new int[]{numberMap.get(difference), index};
} else {
numberMap.put(nums[index], index);
}
}
return new int[0];
}
}A
HashMapcallednumberMapis created. This map will store numbers from thenumsarray as keys and their corresponding indices as values.A loop iterates through each element in the
numsarray. For each number (nums[index]), the code calculates thedifferenceastarget - nums[index]. This represents the value needed to reach the target when added to the current number.The method checks if
differenceis already a key innumberMap. If it is found, it means that there exists a number previously encountered that, when added to the current number (nums[index]), equals thetarget. The method then returns an array containing:The index of the number that matches the difference (
numberMap.get(difference)).The current index (
index).
If the difference is not found in the map, the current number and its index are added to
numberMap. This allows the program to keep track of previously encountered numbers for future lookups.If the loop completes without finding any valid pairs, the method returns an empty array. This indicates that no two indices were found that satisfy the condition.

Last updated