
Sponsored
Sponsored
This approach leverages a hash map (or dictionary) to solve the problem efficiently. By taking advantage of the average O(1) time complexity for insert and lookup operations in hash maps, we can create a mapping between elements and their indices (or frequencies, depending on the problem requirements). This method not only offers efficient retrieval but also makes it easier to track elements as we iterate through the data structure.
Time Complexity: O(n), where n is the number of elements in the input list.
Space Complexity: O(n), due to the storage of numbers in the hash map.
This Java solution uses a HashMap to store elements and their indices. During each iteration, the complement is calculated, and the map is checked for its presence. If the complement is found, the indices are returned.
This approach utilizes a two-pointer technique which is particularly effective when the input is sorted (or can be sorted) without significantly impacting performance. By using two pointers to traverse the array from both ends, we can efficiently find the pair of elements that sum to the target. Note that this approach is based on the assumption that sorting the input is feasible and will not exceed time limits.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) because we store tuples of indices and numbers.
1function twoSum(nums, target) {
2 const numsWithIndex = nums.map((num, index) => ({ num, index }));
3 numsWithIndex.sort((a, b) => a.num - b.num);
4 let left = 0, right = numsWithIndex.length - 1;
5 while (left < right) {
6 const sum = numsWithIndex[left].num + numsWithIndex[right].num;
7 if (sum === target) {
8 return [numsWithIndex[left].index, numsWithIndex[right].index];
9 } else if (sum < target) {
10 left++;
11 } else {
12 right--;
13 }
14 }
15 return [];
16}This JavaScript solution sorts the array with indices preserved, and then uses two pointers to find the target sum. It adjusts the pointers depending on the result of the sum relative to the target.