A Seat at the Hashtable
The solution to the Two Sum question:
The two-sum problem solution wants us to provide two indices from an array whose numbers add up to a target number designated at the outset.
First, I thought to create a double loop, where each index checked against every other index to see if the two added up to the target.
While technically this would work, it is known as a 'brute force solution' and not efficient Big O wise, considering the more integers in the array, the longer the looping would take. A simpler solution exists.
Turns out, all this takes is one loop and a hash table.
The hashtable, an empty object we declare when we first set the function in motion, will hold both a number from the array and its index displayed as such: ( number: index).
Therefore:
We (for) loop through the entire array, and for each index, we subtract the number at that index from the given target. This difference will be stored in the variable "complement."
If the hashtable contains the complement using the 'dot has own property method,' well, then we have a winner and return from the hashtable the index of the complementary number along with the index of whatever number we used to find the complement.
If the hashtable does not yet have the complement well, we assign the index and its' number to the hashtable.
We return null if we cannot add up to the target.
I've provided a picture of my code itself.
Client Solutions Manager
1 年A seat at the hashtable ?? fascinating stuff!!
Writer of code and screenplays
1 年For more posts on Leet Code questions, app building, and languages, check out the entire journal here: https://gshportfolio.vercel.app/livejournal