This approach uses a simple brute force algorithm, which consists of checking each pair of numbers to see if they add up to the target. Although this is straightforward, it is not the most efficient method. We loop through each number in the array using two nested loops, effectively trying all combinations of two numbers.
Time Complexity: O(n^2)
Space Complexity: O(1)
1function twoSum(nums, target) {
2 for (let i = 0; i < nums.length; i++) {
3 for (let j = i + 1; j < nums.length; j++) {
4 if (nums[i] + nums[j] === target) {
5 return [i, j];
6 }
7 }
8 }
9 return [];
10}
11
12let nums = [2, 7, 11, 15];
13let target = 9;
14let result = twoSum(nums, target);
15console.log(result);
The JavaScript solution uses nested loops to find two array elements that sum up to the target. Once it finds such a pair, it returns their indices in an array.
This efficient approach utilizes a hash map to store the difference between the target and the current element (called 'complement') as the key and the element's index as the value. As we iterate through the array, we check if the current element is a key in the hash map, which indicates that its complement was seen earlier, thus allowing us to retrieve the correct indices quickly.
Time Complexity: O(n)
Space Complexity: O(n)
1import java.util.*;
2
3public class Main {
4 public static int[] twoSum(int[] nums, int target) {
5 Map<Integer, Integer> map = new HashMap<>();
6 for (int i = 0; i < nums.length; i++) {
7 int complement = target - nums[i];
8 if (map.containsKey(complement)) {
9 return new int[] { map.get(complement), i };
10 }
11 map.put(nums[i], i);
12 }
13 return new int[] {};
14 }
15
16 public static void main(String[] args) {
17 int[] nums = { 2, 7, 11, 15 };
18 int target = 9;
19 int[] result = twoSum(nums, target);
20 System.out.println("[" + result[0] + ", " + result[1] + "]");
21 }
22}
The Java solution employs a HashMap that keeps the integer values as keys and indices as values. It efficiently finds the pair whose sum equals the target by checking for each complement in the map.