
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 Python solution iterates over the list of numbers while maintaining a hash map of previously visited numbers and their indices. For each number, it calculates the complement (i.e., the difference between the target and the current number). If the complement is found in the hash map, the indices of the current number and the complement are returned as they sum to the target.
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.