A Seat at the Hashtable

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.



Sierra McAliney

Client Solutions Manager

1 年

A seat at the hashtable ?? fascinating stuff!!

Grant Harris

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

回复

要查看或添加评论,请登录

Grant Harris的更多文章

  • First Unique Character in a String

    First Unique Character in a String

    We want to find the index of the first character in a string that does not later repeat itself. We break out a…

    5 条评论
  • Haystacks and Needles

    Haystacks and Needles

    Strings within strings, aka substrings, aka needles, are searchable by looping through each index of the haystack…

  • How Two Linked Lists Became Merged Into One...

    How Two Linked Lists Became Merged Into One...

    Our journey centers around Dummy, a burgeoning linked list. Dummy is destined to house nodes, each bearing a value and…

  • Palindrome ≠ Emordnilap

    Palindrome ≠ Emordnilap

    While we know the word palindrome is not a palindrome, we sometimes need the computer to confirm whether an integer is…

    2 条评论
  • Permutations!

    Permutations!

    The permutations question wants you to take an array and determine how many permutations you can make. Every time we…

    3 条评论
  • Reverse Reverse

    Reverse Reverse

    For this post, I'll review how to reverse integers, another Leet Code style question. The caveat is that the integers…

    1 条评论

社区洞察

其他会员也浏览了