Problem Solving - Sum of Two Numbers (Hash Table)
The twoSum
function is designed to find two numbers in an array (numbers
) that add up to a specific target value. The function returns the indices of these two numbers in the form of an array. Here's a step-by-step explanation:
function twoSum(numbers = [], target = 0) {
const hashTable = {};for (let i = 0; i < numbers.length; i++) {const remaining = target - nums[i]if (hashTable[remaining] !== undefined) {return [hashTable[remaining], i]}hashTable[numbers[i]] = i;}return [];};
Function Breakdown:
Input Parameters:
nums
: An array of numbers.target
: A single number representing the target sum.
Output:
- An array containing the indices of the two numbers that add up to the
target
. If no such pair is found, the function returns an empty array.
- An array containing the indices of the two numbers that add up to the
Explanation:
Initialization:
A hash table (or object)
hashTable
is initialized to store the indices of numbers encountered so far.A loop is set up to iterate over the
nums
array, where i
is the current index.For each number in the array, the function calculates the
remaining
value that, when added to nums[i]
, would equal the target
.remaining
value already exists in the hashTable
.target
. The function then returns an array with the index of the remaining
value and the current index i
.remaining
value is not found in the hash table, the current number (nums[i]
) and its index (i
) are stored in the hashTable
.target
, the function returns an empty array, indicating that no such pair exists.Example:
Suppose
nums = [2, 7, 11, 15]
andtarget = 9
.
Iteration 1:i = 0
,nums[0] = 2
,remaining = 9 - 2 = 7
hashTable = {}
(7 is not inhashTable
)
hashTable
becomes{2: 0}
i = 1
,nums[1] = 7
,remaining = 9 - 7 = 2
hashTable = {2: 0}
(2 is inhashTable
)
- The function returns
[0, 1]
sincenums[0] + nums[1] = 2 + 7 = 9
.
This solution is efficient with a time complexity of O(n), where n is the length of the nums
array. This is because each element is processed only once in a single pass through the array.
0 Comments