<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: noam sauer-utley</title>
    <description>The latest articles on DEV Community by noam sauer-utley (@noamsauerutley).</description>
    <link>https://dev.to/noamsauerutley</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F284012%2F2b57ce55-cbf3-4197-92b3-b1cf9e1927b2.jpg</url>
      <title>DEV Community: noam sauer-utley</title>
      <link>https://dev.to/noamsauerutley</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/noamsauerutley"/>
    <language>en</language>
    <item>
      <title>Solving Balanced Brackets in Javascript with Stacks</title>
      <dc:creator>noam sauer-utley</dc:creator>
      <pubDate>Sat, 29 Feb 2020 21:31:09 +0000</pubDate>
      <link>https://dev.to/noamsauerutley/solving-balanced-brackets-in-javascript-with-stacks-1cal</link>
      <guid>https://dev.to/noamsauerutley/solving-balanced-brackets-in-javascript-with-stacks-1cal</guid>
      <description>&lt;h3&gt;
  
  
  &lt;a href="https://github.com/noamsauerutley/balanced-brackets"&gt;GitHub Repo with completed solution code and test suite&lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;What is the aim of the Balanced Brackets algorithm challenge?&lt;/p&gt;

&lt;blockquote&gt;
&lt;h1&gt;
  
  
  “Given a string containing brackets, determine if all brackets have a matching counterpart. If all brackets in the string form balanced pairs, return true. If not, return false”
&lt;/h1&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--3dLAUlpn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2AYC5UpZvSmnWCIBGuicOR7Q.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3dLAUlpn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2AYC5UpZvSmnWCIBGuicOR7Q.jpeg" alt="" width="588" height="259"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Note&lt;/strong&gt;: I use the word “&lt;a href="https://en.wikipedia.org/wiki/Bracket"&gt;brackets&lt;/a&gt;” in this case to refer to parentheses, curly braces, square brackets, and angle brackets (‘), {, [, &amp;lt;, &amp;gt;, ], }, )’). Not every challenge might require you to include all four types!&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The first time I looked at this problem, my first instinct was to try to just sort the string into substrings based on whether each character was an open or closing bracket and compare the lengths of the substrings.&lt;/p&gt;

&lt;p&gt;That approach may work on the occasional simple string, but it breaks down pretty quickly. We need to know not only that there is a closing bracket for each opening bracket, but also that the specific type of opening and closing brackets match each other. Not only that, if we wanted this function to be useful for any sort of IDE syntax highlighting or other practical application, it would need to identify not only that the opening and closing brackets exist in the correct number and type, but also that they are arranged in the correct order — that every opening bracket has a matching closing bracket in the correct place in the string to actually close it. &lt;/p&gt;

&lt;p&gt;This is what is meant by saying that brackets are “balanced” — not only do they exist in the correct number of matching pairs, but that those pairs are arranged correctly so that the closing brackets can balance the opening brackets.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZZhidh0p--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2032/1%2AWsOuFrzz-CNoHl5dKiGdSg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZZhidh0p--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2032/1%2AWsOuFrzz-CNoHl5dKiGdSg.png" alt="" width="880" height="679"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;My initial idea for sorting out the string into substrings and comparing substring lengths would clearly break down at multiple intervals of the challenge. &lt;/p&gt;

&lt;p&gt;I needed another approach.&lt;/p&gt;

&lt;h2&gt;
  
  
  STACKS
&lt;/h2&gt;

&lt;p&gt;The tool I ultimately used to solve this algorithm was a data structure I hadn’t used before. &lt;/p&gt;

&lt;p&gt;I’ve &lt;a href="https://levelup.gitconnected.com/solving-the-ransom-note-algorithm-in-javascript-72ebe8acb268"&gt;written&lt;/a&gt; &lt;a href="https://levelup.gitconnected.com/find-all-permutations-of-a-string-in-javascript-af41bfe072d2"&gt;before&lt;/a&gt; about the benefits of using &lt;a href="https://en.wikipedia.org/wiki/Hash_table"&gt;hash tables&lt;/a&gt; and &lt;a href="https://en.wikipedia.org/wiki/Master_theorem_(analysis_of_algorithms)"&gt;recursive trees&lt;/a&gt; to break down complicated tasks. I know that &lt;a href="https://www.geeksforgeeks.org/data-structures/"&gt;data structures&lt;/a&gt; can make amazing tools for deconstructing problems that require &lt;a href="https://en.wikipedia.org/wiki/Algorithm"&gt;algorithmic solutions&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;But before trying to tackle this particular problem, I hadn’t had many encounters with &lt;a href="https://medium.com/@hitherejoe/data-structures-stacks-queues-a3b3591c8cb0"&gt;stacks&lt;/a&gt;¹. &lt;/p&gt;

&lt;p&gt;In Javascript, I like to think of them as an &lt;a href="https://www.geeksforgeeks.org/arrays-in-javascript/"&gt;array&lt;/a&gt; with some restrictive rules. &lt;/p&gt;

&lt;p&gt;Normally, arrays in Javascript can be manipulated in a really wide variety of ways. That’s what makes them so handy. That’s the reason why I start most algorithmic solutions by making an empty array. We’ll almost always need one as an environment for manipulating or organizing our data.&lt;/p&gt;

&lt;p&gt;Stacks in Javascript are utilized by only operating on an array using the &lt;strong&gt;&lt;a href="https://www.geeksforgeeks.org/javascript-array-prototype-push-function/"&gt;push&lt;/a&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;a href="https://www.geeksforgeeks.org/javascript-array-prototype-pop/"&gt;pop&lt;/a&gt;&lt;/strong&gt; methods. These methods would push a new element onto the top of the stack, or pop it back off the top, respectively.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--tZi35ywb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2AgDhgbBYPS9losgQh02BmsQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--tZi35ywb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2AgDhgbBYPS9losgQh02BmsQ.png" alt="" width="332" height="273"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;While the elements of a regular array can be accessed from any direction (unshifted off the front, pushed onto the back, sliced right into or out of the middle, or just edited in place), I think of a stack as being an array that’s been all sealed up so that it’s inaccessible, except for one door. New things can be pushed in through the door, but then only the most recently added thing, the one directly in front of the door, can be accessed or manipulated in any way. If that element is removed using &lt;em&gt;&lt;strong&gt;array.pop()&lt;/strong&gt;&lt;/em&gt;, then the element behind it is now available to be changed or removed. However, if it is not removed but instead a new element is pushed in through the door, the previously accessible element becomes inaccessible again.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--tn5e8dGS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2AA-OSrVHrH5HtIaP2qKXAXg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--tn5e8dGS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2AA-OSrVHrH5HtIaP2qKXAXg.png" alt="" width="773" height="540"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This approach is called &lt;strong&gt;FILO&lt;/strong&gt;, or &lt;strong&gt;First In Last Out&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;(This sort of acronym may be familiar to anyone who’s worked in or around kitchens, which are inevitably ruled by the related but opposite law of &lt;strong&gt;FIFO&lt;/strong&gt;, or &lt;strong&gt;First In First Out&lt;/strong&gt; in the attempts to avoid food waste and spoilage.)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Why would we intentionally limit our lovely versatile arrays like this though?&lt;/p&gt;

&lt;p&gt;Well, this process preserves a particular order — the elements can only be removed in the order that they were initially added, preserving the original order, or pattern.&lt;/p&gt;

&lt;p&gt;Which is exactly what we need to do with our brackets — identify not only the number and type of brackets included in our string, but also their specific order.&lt;/p&gt;

&lt;p&gt;So, we know that stacks allow you to manipulate data within an array, while preserving the original ordered patterns of the data, which sounds like what we need to do. Let’s set about actually using this tool in an algorithmic solution to our this challenge.&lt;/p&gt;

&lt;p&gt;So, a bit of pseudocode to get us started:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let isBalanced = (input) =&amp;gt; {
  iterate through input
    if the current element is an opening bracket, record the correct closing bracket
    if the current element is a closing bracket, check the record to make sure it is the correct closing bracket
  if all the opening and closing brackets are matched and in the correct order, return true, otherwise return false
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I know that using a &lt;strong&gt;stack&lt;/strong&gt;, I can preserve a record of the order of my brackets, which will allow me to check if they are all correctly balanced (all opening and closing brackets have a match, and they are in the correct order to balance each other) or not.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let isBalanced = (input) =&amp;gt; {

  let brackets = "[]{}()&amp;lt;&amp;gt;"
  let stack = []

  for(let bracket of input) {
    // record order on the stack
    // check this record to make sure the brackets are all balanced
  }
  return true ? true : false
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First, I’m making a few workhorse variables for myself.&lt;/p&gt;

&lt;p&gt;I’m saving a string listing all my potential opening and closing brackets to a variable named &lt;strong&gt;brackets&lt;/strong&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;&lt;strong&gt;Note&lt;/strong&gt;: I am pairing the opening and closing brackets together in this string.&lt;/em&gt;&lt;br&gt;
&lt;em&gt;**This is important. *&lt;/em&gt;*&lt;br&gt;
&lt;em&gt;My particular solution &lt;strong&gt;would not work&lt;/strong&gt; if the bracket string were to be written as “&lt;strong&gt;[{(&amp;lt;]})&amp;gt;&lt;/strong&gt;”, for example.&lt;/em&gt;&lt;br&gt;
&lt;em&gt;The brackets can be in any order by type (e.g. “&lt;strong&gt;()[]{}&amp;lt;&amp;gt;&lt;/strong&gt;” and “&lt;strong&gt;&amp;lt;&amp;gt;(){}[]&lt;/strong&gt;” are both perfectly fine), but the &lt;strong&gt;opening and closing brackets must be written together&lt;/strong&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The next variable I’m creating is just an empty array, which we can call &lt;strong&gt;stack&lt;/strong&gt;, as this will be our stack.&lt;/p&gt;

&lt;p&gt;I’ve sketched out an initial loop through our input string, populated only by pseudocode at this point. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Note&lt;/strong&gt;: this loop is iterating through the elements of input, not the indexes. Personally, I enjoy using &lt;strong&gt;&lt;a href="https://alligator.io/js/for-of-for-in-loops/"&gt;for…in / for…of loops&lt;/a&gt;&lt;/strong&gt;, but you can always use a more traditional for loop (e.g. “&lt;strong&gt;for (let i = 0; i &amp;lt; input.length, i++)&lt;/strong&gt;”) and still utilize this solution with minor modifications if you prefer.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Our function’s only remaining job will be to return either true or false upon the loop’s resolution.&lt;/p&gt;

&lt;p&gt;Time to actually develop our stack and put it to use!&lt;/p&gt;

&lt;p&gt;First, another workhorse variable within the loop itself:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let isBalanced = (input) =&amp;gt; {

  let brackets = "[]{}()&amp;lt;&amp;gt;"
  let stack = []

  for(let bracket of input) {
    let bracketsIndex = brackets.indexOf(bracket)

    // record order on the stack
    // check this record to make sure the brackets are all balanced
  }
  return true ? true : false
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;bracketsIndex&lt;/em&gt;&lt;/strong&gt;: I want to make sure the role of this variable is quite clear before moving forward!&lt;/p&gt;

&lt;p&gt;We are iterating through &lt;strong&gt;&lt;em&gt;input&lt;/em&gt;&lt;/strong&gt;, the string of brackets that is passed into the function for testing. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;bracketsIndex&lt;/em&gt; is NOT the index in &lt;em&gt;input&lt;/em&gt; of the current &lt;em&gt;bracket&lt;/em&gt;.&lt;/strong&gt;*&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;bracketsIndex&lt;/em&gt;&lt;/strong&gt; is looking up the &lt;strong&gt;index&lt;/strong&gt; of the current &lt;strong&gt;_bracket _&lt;/strong&gt;in our previously saved &lt;strong&gt;&lt;em&gt;brackets&lt;/em&gt;&lt;/strong&gt; variable. So if the first &lt;strong&gt;&lt;em&gt;bracket&lt;/em&gt;&lt;/strong&gt; in &lt;strong&gt;&lt;em&gt;input&lt;/em&gt;&lt;/strong&gt; were a “&lt;strong&gt;(&lt;/strong&gt;“, its &lt;strong&gt;&lt;em&gt;bracketsIndex&lt;/em&gt;&lt;/strong&gt; would be &lt;strong&gt;4&lt;/strong&gt;. Its &lt;strong&gt;index&lt;/strong&gt; in &lt;strong&gt;&lt;em&gt;input&lt;/em&gt;&lt;/strong&gt; is, of course, &lt;strong&gt;0&lt;/strong&gt;, but the &lt;strong&gt;index&lt;/strong&gt; of “&lt;strong&gt;(&lt;/strong&gt;“ in &lt;strong&gt;&lt;em&gt;brackets&lt;/em&gt;&lt;/strong&gt; is &lt;strong&gt;4&lt;/strong&gt;, so its &lt;strong&gt;&lt;em&gt;bracketsIndex&lt;/em&gt;&lt;/strong&gt; is &lt;strong&gt;4&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;Remember the bit about how the order of the brackets in the brackets string was important? We’re getting there.&lt;/p&gt;

&lt;p&gt;So now, we have a variable, &lt;strong&gt;&lt;em&gt;bracketsIndex&lt;/em&gt;&lt;/strong&gt;, that can look up our current bracket in the &lt;strong&gt;&lt;em&gt;brackets&lt;/em&gt;&lt;/strong&gt; variable.&lt;/p&gt;

&lt;p&gt;Now, we can finally start putting our stack to work.&lt;/p&gt;

&lt;p&gt;Because of the way we organized our &lt;strong&gt;&lt;em&gt;brackets&lt;/em&gt;&lt;/strong&gt; reference string, we know that opening brackets have even indexes (0, 2, 4, &amp;amp; 6) and closing brackets have odd indexes (1, 3, 5, 7).&lt;/p&gt;

&lt;p&gt;So, if our current &lt;strong&gt;&lt;em&gt;bracketsIndex&lt;/em&gt;&lt;/strong&gt; is even, we know that the current &lt;strong&gt;&lt;em&gt;bracket&lt;/em&gt;&lt;/strong&gt; is an opening bracket. &lt;/p&gt;

&lt;p&gt;We can test for this using a &lt;a href="https://en.wikipedia.org/wiki/Modulo_operation"&gt;modulo operator&lt;/a&gt;. Modulo operations, called in Javascript by the &lt;strong&gt;modulo operator&lt;/strong&gt;, i.e. “&lt;strong&gt;%&lt;/strong&gt;” (commonly called the percent sign), divide a first number by a second number, then return the remainder. So, one way to test for even or odd numbers is to run &lt;em&gt;number % 2 === 0&lt;/em&gt;. Two will divide evenly into an even number, yielding a remainder of zero (returning true) while it will not into an odd number (returning false). &lt;/p&gt;

&lt;p&gt;We can then push the location in &lt;strong&gt;&lt;em&gt;brackets&lt;/em&gt;&lt;/strong&gt; of the needed closing bracket onto the stack, by finding the bracket with index &lt;strong&gt;&lt;em&gt;bracketsIndex&lt;/em&gt;&lt;/strong&gt; + 1. Again, because of the way that we wrote our &lt;strong&gt;&lt;em&gt;brackets&lt;/em&gt;&lt;/strong&gt; string, an opening bracket will always be immediately followed by its matching closing bracket. Thanks to this, we can increment the &lt;strong&gt;&lt;em&gt;bracketsIndex&lt;/em&gt;&lt;/strong&gt; of any opening bracket to find the address of its closing match.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let isBalanced = (input) =&amp;gt; {

  let brackets = "[]{}()&amp;lt;&amp;gt;"
  let stack = []

  for(let bracket of input) {
    let bracketsIndex = brackets.indexOf(bracket)

    // if bracket is an opening bracket
     if(bracketsIndex % 2 === 0) {
       // push the closing bracket onto the stack
      stack.push(bracketsIndex + 1)
    } else {
      //do something
    }
  }
  return true ? true : false
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, as we iterate through our input, our stack will keep a record of the closing brackets needed for the input string to be balanced. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Note&lt;/strong&gt;: The &lt;strong&gt;bracketsIndex&lt;/strong&gt;, an integer, is what is being pushed onto the stack, not the closing bracket itself.&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt; If our loop had iterated through the elements “&lt;strong&gt;(, &amp;lt;, [“&lt;/strong&gt;, the stack would hold the indexes in &lt;em&gt;&lt;strong&gt;brackets&lt;/strong&gt;&lt;/em&gt; of “&lt;strong&gt;), &amp;gt;, ]&lt;/strong&gt;” and thus would be &lt;strong&gt;[5,  7, 1]&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Our loop will continue this task as long as we keep hitting opening brackets.&lt;/p&gt;

&lt;p&gt;That’s cool. What happens when we hit a closing bracket though?&lt;/p&gt;

&lt;p&gt;If the current &lt;strong&gt;&lt;em&gt;bracket&lt;/em&gt;&lt;/strong&gt; of &lt;strong&gt;&lt;em&gt;input&lt;/em&gt;&lt;/strong&gt; is a closing bracket, and therefore has an odd index, then (due to our conditional that runs based on the even/odd test of its &lt;strong&gt;&lt;em&gt;bracketsIndex&lt;/em&gt;&lt;/strong&gt;), a new task will run.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Array.pop()&lt;/strong&gt; removes the most recent addition from our stack, changing the length of the array, and returns that removed element, allowing us to reference that element if needed. &lt;/p&gt;

&lt;p&gt;So, If the current bracket is closing, we’ll pop the last element off the stack and compare the two. If our brackets are balanced, they should match.&lt;/p&gt;

&lt;p&gt;This is the whole purpose of using the stack — as we iterate through our input string, the needed closing bracket is pushed onto the stack for each opening bracket, then popped off when the matching closing bracket is reached. If something in the stack breaks this pattern, then we know that our input string is not balanced.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let isBalanced = (input) =&amp;gt; {

  let brackets = "[]{}()&amp;lt;&amp;gt;"
  let stack = []

  for(let bracket of input) {
    let bracketsIndex = brackets.indexOf(bracket)

    if(bracketsIndex % 2 === 0) {
      stack.push(bracketsIndex + 1)
    } else {
      if(stack.pop() !== bracketsIndex) {
        return false;
      }
    }
  }
  // return true or false
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt; If our loop had iterated through the elements “&lt;strong&gt;(, &amp;lt;, [“&lt;/strong&gt;, the stack would hold the indexes in &lt;em&gt;&lt;strong&gt;brackets&lt;/strong&gt;&lt;/em&gt; of “&lt;strong&gt;), &amp;gt;, ]&lt;/strong&gt;” and thus would be &lt;strong&gt;[5, 7, 1]&lt;/strong&gt;. &lt;br&gt;
If the following iteration hit the element “&lt;strong&gt;]&lt;/strong&gt;”, then our expression would check &lt;em&gt;&lt;strong&gt;stack.pop()&lt;/strong&gt;&lt;/em&gt; (i.e. &lt;strong&gt;1&lt;/strong&gt;) against the &lt;em&gt;&lt;strong&gt;bracketIndex&lt;/strong&gt;&lt;/em&gt; of the current &lt;em&gt;&lt;strong&gt;bracket&lt;/strong&gt;&lt;/em&gt; (the current bracket being &lt;strong&gt;]&lt;/strong&gt; would have a &lt;em&gt;&lt;strong&gt;bracketIndex&lt;/strong&gt;&lt;/em&gt; of &lt;strong&gt;1&lt;/strong&gt;) and, as they are indeed equal, would return true, allowing it to move on to the next element in &lt;em&gt;&lt;strong&gt;input&lt;/strong&gt;&lt;/em&gt;. The &lt;em&gt;&lt;strong&gt;stack&lt;/strong&gt;&lt;/em&gt; going forward would be &lt;strong&gt;[5, 7]&lt;/strong&gt;, as the execution of &lt;em&gt;&lt;strong&gt;stack.pop()&lt;/strong&gt;&lt;/em&gt; permanently removed &lt;strong&gt;1&lt;/strong&gt; from the &lt;em&gt;&lt;strong&gt;stack&lt;/strong&gt;&lt;/em&gt; array.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We need to check for one more thing though — when this loop resolves, the stack should be empty. If it’s not, that means there’s an extra unbalanced bracket or more left over.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let isBalanced = (input) =&amp;gt; {

  let brackets = "[]{}()&amp;lt;&amp;gt;"
  let stack = []

  for(let bracket of input) {
    let bracketsIndex = brackets.indexOf(bracket)

    if(bracketsIndex % 2 === 0) {
      stack.push(bracketsIndex + 1)
    } else {
      if(stack.pop() !== bracketsIndex) {
        return false;
      }
    }
  }
  return stack.length === 0
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, I check that &lt;em&gt;&lt;strong&gt;stack&lt;/strong&gt;&lt;/em&gt; has a length of zero in the final boolean return. The expression &lt;em&gt;stack.length === 0&lt;/em&gt; will return the boolean we need here. &lt;/p&gt;

&lt;p&gt;If the whole loop runs without returning false and the stack is empty when it resolves, we know our input string is balanced and the function should return true. Otherwise, our function should return false.&lt;/p&gt;

&lt;p&gt;Let’s run this function into the console and see what we get!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let isBalanced = (input) =&amp;gt; {

  let brackets = "[]{}()&amp;lt;&amp;gt;"
  let stack = []

  for(let bracket of input) {
    let bracketsIndex = brackets.indexOf(bracket)

    if(bracketsIndex % 2 === 0) {
      stack.push(bracketsIndex + 1)
    } else {
      if(stack.pop() !== bracketsIndex) {
        return false;
      }
    }
  }
  return stack.length === 0
}

isBalanced('()')
&amp;gt; true

isBalanced('()[]{}&amp;lt;&amp;gt;')
&amp;gt; true

isBalanced('([{&amp;lt;&amp;gt;}])')
&amp;gt; true

isBalanced('([])[{}]{(())}')
&amp;gt; true

isBalanced('(')
&amp;gt; false

isBalanced('()]')
&amp;gt; false

isBalanced('([])[{}]{(([))}')
&amp;gt; false

isBalanced('({)')
&amp;gt; false

isBalanced('([)]')
&amp;gt; false

isBalanced('([])[{}]{([)]}')
&amp;gt; false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Great! 🌟 I tested the &lt;em&gt;&lt;strong&gt;isBalanced()&lt;/strong&gt;&lt;/em&gt; function against a variety of balanced and unbalanced strings² and it returned the correct boolean for each one! Unlike my first idea, this function can successfully check for not only the correct number and types of brackets, but also check their specific order to make sure they match up correctly. &lt;/p&gt;

&lt;p&gt;I still want to add one more element of functionality to our function. At the moment, if input contains anything other than pure brackets, our function will break. That’s not going to help us much if we actually wanted to create our own syntax bracket highlighter or other practical application of our function. So, we can add one more conditional into our loop.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let isBalanced = (input) =&amp;gt; {

  let brackets = "[]{}()&amp;lt;&amp;gt;"
  let stack = []

  for(let bracket of input) {
    let bracketsIndex = brackets.indexOf(bracket)

    if (bracketsIndex === -1){
      continue
    }

    if(bracketsIndex % 2 === 0) {
      stack.push(bracketsIndex + 1)
    } else {
      if(stack.pop() !== bracketsIndex) {
        return false;
      }
    }
  }
  return stack.length === 0
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the current element is not in &lt;em&gt;&lt;strong&gt;brackets&lt;/strong&gt;&lt;/em&gt; (which will yield an index of -1), we simply direct our loop to move on to the next character in our input string. This one change makes our function much more adaptable! &lt;/p&gt;

&lt;p&gt;This algorithm challenge made me really appreciate using a stack, even though that particular data structure had been quite neglected in my previous experience. There are other ways to solve this, but a lot of them involve writing out a lot of repetitive code to test for each individual bracket type, which gave me lots of opportunities to make typos and get bored. &lt;/p&gt;

&lt;p&gt;If you’re having a tough time visualizing the operation of the stack, I recommend adding some &lt;a href="https://www.geeksforgeeks.org/debugging-in-javascript/"&gt;debuggers&lt;/a&gt; or &lt;a href="https://www.geeksforgeeks.org/javascript-console-log-with-examples/"&gt;console.log()&lt;/a&gt;s to this code, and watching the loop play out in your console. &lt;/p&gt;

&lt;p&gt;Not sure where to start? You might try something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let isBalanced = (input) =&amp;gt; {

  let brackets = "[]{}()&amp;lt;&amp;gt;"
  let stack = []

  for(let bracket of input) {
    let bracketsIndex = brackets.indexOf(bracket)
    console.log(`The current element is ${bracket}, which has an index in input of ${input.indexOf(bracket)}, and matches the bracket with index ${bracketsIndex} in brackets`)

    if(bracketsIndex % 2 === 0) {
      stack.push(bracketsIndex + 1)
      console.log(`this is an opening bracket. The address of its matching closing bracket in brackets is ${bracketsIndex + 1}. Adding that index to the stack makes the stack ${stack}`)
    } else {
      console.log(`this is a closing bracket, so ${stack.pop()} is being popped off the stack`)
      if(stack.pop() !== bracketsIndex) {
        return false;
      }
    }
  }
  return stack.length === 0
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hopefully this algorithm challenge gives you the same opportunity it did me — the chance to understand how stacks work, and why they’re such useful tools for problems where a particular order needs to be preserved and checked against.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--sDiWLCW_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2AtOoeIMz9DwPZ52Ewog2W6w.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--sDiWLCW_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2AtOoeIMz9DwPZ52Ewog2W6w.gif" alt="" width="270" height="360"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;This article also addresses the &lt;strong&gt;queue&lt;/strong&gt; data structure, which isn’t strictly relevant to this particular challenge but still nice to know about. While the article is not exclusively stack-focused, it’s one of my favorite stack summaries. I also like &lt;a href="https://medium.com/@_jmoller/javascript-data-structures-stacks-and-queues-ea877d72a5f9"&gt;this one&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;These strings are what I use in the test suite included in the &lt;a href="https://github.com/noamsauerutley/balanced-brackets"&gt;GitHub Repo&lt;/a&gt; for this post, and the &lt;a href="https://github.com/noamsauerutley/balanced-brackets/blob/master/test/balancedBrackets.spec.js"&gt;test file&lt;/a&gt; includes comments that can give you more info about what each different string is testing the function for. &lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>javascript</category>
      <category>algorithms</category>
      <category>stack</category>
    </item>
    <item>
      <title>Solving the Ransom Note Algorithm in Javascript</title>
      <dc:creator>noam sauer-utley</dc:creator>
      <pubDate>Mon, 24 Feb 2020 00:17:36 +0000</pubDate>
      <link>https://dev.to/noamsauerutley/solving-the-ransom-note-algorithm-in-javascript-259</link>
      <guid>https://dev.to/noamsauerutley/solving-the-ransom-note-algorithm-in-javascript-259</guid>
      <description>&lt;h3&gt;
  
  
  &lt;a href="https://github.com/noamsauerutley/ransom-note"&gt;GitHub repo with completed solution code and test suite.&lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;What is the Ransom Note challenge?&lt;/p&gt;

&lt;blockquote&gt;
&lt;h1&gt;
  
  
  ‘Given two strings:
&lt;/h1&gt;
&lt;h1&gt;
  
  
  1. A source string, i.e. the “page”
&lt;/h1&gt;
&lt;h1&gt;
  
  
  2. A desired string, i.e. the “note”
&lt;/h1&gt;
&lt;h1&gt;
  
  
  determine if the desired “note” string can be created using only the letters found in the source “page”.’
&lt;/h1&gt;
&lt;/blockquote&gt;

&lt;p&gt;A visual example of what we’re looking for would be this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--JvAwCqxh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2AdwOyLXK_Ccw_0Sffvapirw.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--JvAwCqxh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2AdwOyLXK_Ccw_0Sffvapirw.jpeg" alt="" width="284" height="149"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So, if we had a page of text, we could chop it up into all its separate letters, then glue them onto a new page to form a new word or phrase of our choosing.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Esy8HGAr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2Ag2MeItkOPD6K0PG_7GVZ5w.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Esy8HGAr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2Ag2MeItkOPD6K0PG_7GVZ5w.jpeg" alt="" width="880" height="681"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Ok, so let’s get started!&lt;/p&gt;

&lt;p&gt;I like to start with a little bit of pseudocode, just so I can write out my aims in a programming context.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let canMakeNote = (source, note) =&amp;gt; {
    if (source contains all the letters needed to make note){
      return true
    }else{
      return false
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So here we have a function called &lt;strong&gt;&lt;em&gt;canMakeNote&lt;/em&gt;&lt;/strong&gt;, whose job is to see if the &lt;strong&gt;&lt;em&gt;source&lt;/em&gt;&lt;/strong&gt; string contains all the letters needed to create the desired &lt;strong&gt;&lt;em&gt;note&lt;/em&gt;&lt;/strong&gt; string. If that is true, it should return &lt;strong&gt;&lt;em&gt;true&lt;/em&gt;&lt;/strong&gt;, and if not, &lt;strong&gt;&lt;em&gt;false&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;However, “if source contains all letters needed to create note” is doing a &lt;strong&gt;lot&lt;/strong&gt; of heavy lifting in the above pseudocode. Let’s start at the beginning.&lt;/p&gt;

&lt;p&gt;We know one thing right away: If the &lt;strong&gt;&lt;em&gt;source&lt;/em&gt;&lt;/strong&gt; string is shorter than the &lt;strong&gt;&lt;em&gt;note&lt;/em&gt;&lt;/strong&gt; string, we will not be able to make the note. There’s no way that we’ll have all the letters we need.&lt;/p&gt;

&lt;p&gt;So first things first, we’ll need to compare the length of our two strings. If the &lt;strong&gt;&lt;em&gt;source&lt;/em&gt;&lt;/strong&gt; string is too short, we won’t need to bother with anything else, and can immediately return &lt;strong&gt;&lt;em&gt;false&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;However, strings can be… messy. &lt;/p&gt;

&lt;p&gt;They could include whitespaces, which I’m not going to track as if they were a letters — if I were cutting letters out of a newspaper or magazine and gluing them onto paper, I wouldn’t cut out and paste on spaces. Counting each whitespace as a letter could be an interesting variation of this challenge, but I’m not going to explore that in this solution. &lt;/p&gt;

&lt;p&gt;So, if whitespaces don’t count as letters, they’ll distort our ability to measure the length of our strings. Not good.&lt;/p&gt;

&lt;p&gt;Plus, the strings might contain both capital and lowercase letters. This won’t affect our judgement of the length of the strings, but it will become an issue further down the line when we begin attempting to compare the content of the strings. For our purposes, “&lt;strong&gt;A&lt;/strong&gt;” is the same as “&lt;strong&gt;a&lt;/strong&gt;”. After all, the iconic ransom note is defined by its higgledy-piggledy mix of upper and lower cased letters. The computer, on the other hand, sees “&lt;strong&gt;A&lt;/strong&gt;” and “&lt;strong&gt;a&lt;/strong&gt;” as completely different characters. &lt;/p&gt;

&lt;p&gt;So that gives us two things we’ll need to account for as we compare our input strings, whitespaces and character case.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;**Note&lt;/em&gt;&lt;em&gt;: Some variations of this challenge will provide the input and desired output parameters in the form of arrays of letters, all tidy and ready to go. That’s great! If you run across a challenge like that, you can just skip this step! However, I wanted to provide a solution that accounts for input / desired output in string form.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;To clean up our messy strings and transform them into something more convenient to our purposes, let’s make a &lt;a href="https://vanillajstoolkit.com/helpers/"&gt;helper function&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I’ll need to account for the whitespaces and character case, and, as this is an algorithmic challenge, I’m going to go ahead and transform our strings into arrays, so that each character will be individually separate, and our data will be in a convenient form for iteration, manipulation, and comparison.&lt;/p&gt;

&lt;p&gt;First, I’ll pseudocode it out:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let clean = (input) =&amp;gt; {
  remove whitespaces from input
  lowercase input
  transform input into an array
  return the cleaned &amp;amp; transformed input
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So we’ve got a handy list of what our string cleaning helper function needs to do.&lt;/p&gt;

&lt;p&gt;First, the whitespaces.&lt;/p&gt;

&lt;p&gt;Whenever I need to identify and manipulate a certain character or characters in a string, I think of &lt;a href="https://www.regular-expressions.info/"&gt;RegEx&lt;/a&gt;. RegEx is the shorthand reference for a“&lt;a href="https://en.wikipedia.org/wiki/Regular_expression"&gt;Regular Expression&lt;/a&gt;”. What is a that?&lt;/p&gt;

&lt;h3&gt;
  
  
  RegEx
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;A &lt;strong&gt;regular expression&lt;/strong&gt;, &lt;strong&gt;regex&lt;/strong&gt; or &lt;strong&gt;regexp&lt;/strong&gt; (sometimes called a &lt;strong&gt;rational expression&lt;/strong&gt;) is a sequence of &lt;a href="https://en.wikipedia.org/wiki/Character_(computing)"&gt;characters&lt;/a&gt; that define a &lt;em&gt;search &lt;a href="https://en.wikipedia.org/wiki/Pattern_matching"&gt;pattern&lt;/a&gt;&lt;/em&gt;. Usually such patterns are used by &lt;a href="https://en.wikipedia.org/wiki/String_searching_algorithm"&gt;string searching algorithms&lt;/a&gt; for “find” or “find and replace” operations on &lt;a href="https://en.wikipedia.org/wiki/String_(computer_science)"&gt;strings&lt;/a&gt;, or for input validation.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;What can RegEx search patterns do? They’re great at collecting all the characters in a string that match a given search criteria, then collecting or manipulating them as directed. This can be incredibly handy, making things that would otherwise be laborious and complicated relatively quick. The tradeoff is that performing RegEx find and replace operations can be &lt;a href="https://www.loggly.com/blog/regexes-the-bad-better-best/"&gt;computationally expensive&lt;/a&gt;! Which should be considered when RegEx is being considered for manipulating extremely large strings. However, for our purposes at this time, RegEx is just what the doctor ordered.&lt;/p&gt;

&lt;p&gt;I’ll be honest, I’m not an expert who’s memorized all the different RegEx patterns and their meanings. I know enough to be able to quickly recall my most-used patterns, but mostly, I’ve had great success with just developing the ability to identify when I’m looking at a problem that would be eased by the use of RegEx. Then, a quick google of the type of find and replace operation I want to perform with the keyword “RegEx” and perhaps the language of the code I’m currently writing usually yields results within the first few links.&lt;/p&gt;

&lt;p&gt;In this case, I googled “javascript regex remove all whitespaces from string” and was promptly provided with the appropriate RegEx pattern for my needs.&lt;/p&gt;

&lt;p&gt;OK, enough about RegEx! Back to our string-cleaning helper function.&lt;/p&gt;

&lt;p&gt;I can combine Javascript’s &lt;a href="https://www.w3schools.com/jsref/jsref_replace.asp"&gt;***replace&lt;/a&gt;*** method with my chosen RegEx pattern, to replace every whitespace in my string with nothing, therefore stripping them out entirely. The RegEx search pattern that I chose also removes line breaks, and any other sorts of “blank” characters it might encounter.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let clean = (input) =&amp;gt; {
  input.replace(/\s/g,'')
  lowercase input
  transform input into an array
  return the cleaned &amp;amp; transformed input
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;input&lt;/em&gt;&lt;/strong&gt; is the name of our argument, which can be any string passed into the function. &lt;strong&gt;&lt;em&gt;/\s/g&lt;/em&gt;&lt;/strong&gt; is the RegEx search pattern to identify all whitespaces / blank characters, and the empty string that follows tells &lt;em&gt;**input.replace *&lt;/em&gt;*that we want to replace the whitespaces with nothing. Altogether, this combo will strip all the blank characters from our input string. &lt;/p&gt;

&lt;p&gt;Whitespaces handled. ✔️&lt;/p&gt;

&lt;p&gt;Next on our list is character case.&lt;/p&gt;

&lt;p&gt;Lucky for us, Javascript comes complete with its own &lt;a href="https://www.w3schools.com/jsref/jsref_tolowercase.asp"&gt;***toLowerCase&lt;/a&gt;*** method, which does pretty much what it says on the tin. When called on a string, it will transform all capital letters in the string to lowercase letter. So, our &lt;em&gt;**clean&lt;/em&gt;* *function can accomplish the next task on our pseudocode list by calling this method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let clean = (input) =&amp;gt; {
  input.replace(/\s/g,'').toLowerCase()
  transform input into an array
  return the cleaned &amp;amp; transformed input
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Okay, finally, we want to change our stripped and lowercased string into an array of characters, and return the final result. &lt;/p&gt;

&lt;p&gt;Again, Javascript has the relevant method ready and waiting for us, as this is the exact purpose of the&lt;a href="https://www.w3schools.com/jsref/jsref_split.asp"&gt; ***string.split()&lt;/a&gt;*** method. We have to tell the method where we want it to split the string, which we can do by including the trigger character in quotes within the parentheses after the method name. However, as we want to separate out each individual character (rather than splitting at each space, for example, to separate out words, or at final punctuation marks to separate sentences), we put nothing inside the quotes.&lt;/p&gt;

&lt;p&gt;So, our final clean function looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let clean = (input) =&amp;gt; {
    return input.replace(/\s/g,'').toLowerCase().split("")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While the &lt;a href="https://github.com/noamsauerutley/ransom-note"&gt;GitHub repository&lt;/a&gt; for this article includes a testing suite, I also like to use the browser console to quickly check my functions and make sure they’re returning what I want. Let’s see what this &lt;strong&gt;&lt;em&gt;clean&lt;/em&gt;&lt;/strong&gt; function returns when given a quote.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let clean = (input) =&amp;gt; {
    return input.replace(/\s/g,'').toLowerCase().split("")
}

let quote = "Aut Viam Inveniam Aut Faciam"

clean(quote)

&amp;gt; (24) ["a", "u", "t", "v", "i", "a", "m", "i", "n", "v", "e", "n", "i", "a", "m", "a", "u", "t", "f", "a", "c", "i", "a", "m"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;🌟 Great! This is exactly the result we wanted. We now have a cleaning function that can take in a string, downcase any capitals, remove all whitespaces, and return a handy array ready to go for our comparison needs.&lt;/p&gt;

&lt;p&gt;In order to effectively compare our now-transformed strings, we need to track two data elements: the individual characters that we either have available or need, and also frequency with which each character we either have available or need occurs.&lt;/p&gt;

&lt;p&gt;The source text may, for example, contain the letter “e” — but what if our desired output text needs five “e”s? An instance of a matching letter alone is not enough to decide that the source text has what we need. &lt;/p&gt;

&lt;p&gt;In &lt;a href="https://en.wikipedia.org/wiki/Frequency_analysis"&gt;Frequency Analysis&lt;/a&gt;, this is a routine challenge, which is often met with the use of &lt;a href="https://en.wikipedia.org/wiki/Histogram"&gt;Histograms&lt;/a&gt;, which are quite similar to &lt;a href="https://en.wikipedia.org/wiki/Bar_chart"&gt;Bar Charts&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Vh8jGPKS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2AkEpEGOxQw4frW8oxmUIpVA.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Vh8jGPKS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2AkEpEGOxQw4frW8oxmUIpVA.jpeg" alt="" width="482" height="289"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;These graphical tools are a visual representation of the exact two pieces of data we need to track — letter and frequency of occurrence. &lt;/p&gt;

&lt;p&gt;Now, unfortunately I can’t simply show a histogram to my computer. However, I can use a non-graphical data structure to communicate the same information that’s in my histogram.&lt;/p&gt;

&lt;p&gt;Speaking of &lt;a href="https://www.geeksforgeeks.org/data-structures/"&gt; Data Structures&lt;/a&gt;, the more algorithms I solve, the more I appreciate the &lt;a href="https://www.hackerearth.com/practice/data-structures/hash-tables/basics-of-hash-tables/tutorial/"&gt;Hash Table&lt;/a&gt;. The data structure that allows the storage of &lt;a href="https://javascript.info/object"&gt;key-value pairs&lt;/a&gt; is often an effective and efficient tool in tasks that require comparing lots of little bits of data. If you’d like to see another example, my &lt;a href="https://levelup.gitconnected.com/solving-the-two-sum-problem-in-javascript-three-ways-4d43067fcfc7"&gt;set of solutions to the Two Sum Problem &lt;/a&gt;includes a hash-based solution, which is by far the most efficient of the three solutions I explore.&lt;/p&gt;

&lt;p&gt;So when I see a challenge that requires the storage of paired pieces of data, it feels intuitive to at least try storing those pieces of data as key-value pairs.&lt;/p&gt;

&lt;p&gt;Let’s pseudocode out this specific task, just as we’ve done before:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let makeHistogram = (input) =&amp;gt; {
    let histogram = {}

    assign each letter of input to a key in histogram
    assign the occurrence frequency of that letter to the corresponding value

    return histogram
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So we’re setting out to create a hash object which can mimic a frequency occurrence histogram. In it, we want to save each character to a key, then store that character’s occurrence frequency (the number of times it’s repeated) to the value attached to that key.&lt;/p&gt;

&lt;p&gt;Since we’re needing to check each letter, we should start by iterating through our input. I’m assuming the input is an array of relevant lowercase characters, as that’s what our previous &lt;strong&gt;&lt;em&gt;clean&lt;/em&gt;&lt;/strong&gt; helper method returns.&lt;/p&gt;

&lt;p&gt;For each letter, I’ll need to determine if we’ve already encountered it before. If it’s the first instance of that letter in the array, we need to make a new key in our &lt;strong&gt;&lt;em&gt;histogram&lt;/em&gt;&lt;/strong&gt; hash object, and assign it the value &lt;strong&gt;&lt;em&gt;1&lt;/em&gt;&lt;/strong&gt;, for one occurrence. If the letter has occurred earlier in the array and therefore has already had a key created for it, we should not make a new key, but rather add &lt;strong&gt;&lt;em&gt;1&lt;/em&gt;&lt;/strong&gt; to the existing key’s value. &lt;/p&gt;

&lt;p&gt;So, with a bit more pseudocode, we can sketch out our loop structure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let makeHistogram = (input) =&amp;gt; {
    let histogram = {}

    for(let letter of input){
        if the letter has been encountered before,increment the value of the key corresponding to letter by one 
        else create a key for it and assign a value of one
    }  
    return histogram
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As I only have two behavior patterns to choose from, I can write out the &lt;a href="https://en.wikipedia.org/wiki/Conditional_(computer_programming)"&gt;conditional statement &lt;/a&gt;for this using a &lt;a href="https://www.tutorialsteacher.com/csharp/csharp-ternary-operator"&gt;ternary operator&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let makeHistogram = (input) =&amp;gt; {
    let histogram = {}

    for(let letter of input){
        letter in histogram ? histogram[letter] += 1 : histogram[letter] = 1
    }  
    return histogram
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this code, the section before the &lt;strong&gt;&lt;em&gt;?&lt;/em&gt;&lt;/strong&gt; is the &lt;a href="https://www.w3schools.com/js/js_if_else.asp"&gt;if statement&lt;/a&gt;. This is what we’re checking for as we iterate through the input array — for each letter of input, we’re checking to see if it already exists in &lt;strong&gt;&lt;em&gt;histogram&lt;/em&gt;&lt;/strong&gt;. If it does, the first operation which comes right after the &lt;em&gt;**? *&lt;/em&gt;&lt;em&gt;(adding one to the value which corresponds to the letter’s key) should be performed. Otherwise, the second operation which comes after the *&lt;/em&gt;&lt;em&gt;: *&lt;/em&gt;*(creating a key for the letter and assigning it a value of one) should be performed. &lt;/p&gt;

&lt;p&gt;Just as we did with our &lt;strong&gt;&lt;em&gt;clean&lt;/em&gt;&lt;/strong&gt; helper function, let’s throw this into the console and see what it outputs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let quote = "Aut Viam Inveniam Aut Faciam"

let clean = (input) =&amp;gt; {
    return input.replace(/\s/g,'').toLowerCase().split("")
}

let cleanedQuote = clean(quote)

let makeHistogram = (input) =&amp;gt; {
    let histogram = {}

    for(let letter of input){
        letter in histogram ? histogram[letter] += 1 : histogram[letter] = 1
    }  
    return histogram
}

makeHistogram(cleanedQuote)

&amp;gt; {a: 6, u: 2, t: 2, v: 2, i: 4, m: 3, n: 2, e: 1, f: 1, c: 1}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;🌟 Great! This returns a hash object containing each letter from the given input as a key, and the occurrence frequency of that letter as the corresponding value. &lt;/p&gt;

&lt;p&gt;We’ve now organized our data into a structure that we can efficiently test. Enough with the helper functions, we’re finally ready to do something with the very first pseudocode function we wrote!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let canMakeNote = (source, note) =&amp;gt; {
    if (source contains all the letters needed to make note){
      return true
    }else{
      return false
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So this was our original pseudocode. &lt;/p&gt;

&lt;p&gt;First things first, we know we’ll be returning a boolean. Let’s go ahead and create a variable for that return value — I’m going to call it &lt;strong&gt;&lt;em&gt;boolean&lt;/em&gt;&lt;/strong&gt; for ease and give it a default value of false. &lt;/p&gt;

&lt;p&gt;Then, we can use our &lt;strong&gt;&lt;em&gt;clean&lt;/em&gt;&lt;/strong&gt; function to clean up our input. &lt;/p&gt;

&lt;p&gt;That will give us two arrays, the lengths of which we can compare. That way, just as we originally stated, if the &lt;strong&gt;&lt;em&gt;source&lt;/em&gt;&lt;/strong&gt; is longer than the &lt;strong&gt;&lt;em&gt;note&lt;/em&gt;&lt;/strong&gt;, we’ll want to move forward, but if it’s not? We don’t need to do anything else and can immediately return &lt;strong&gt;&lt;em&gt;false&lt;/em&gt;&lt;/strong&gt;. Since we initialized our &lt;strong&gt;&lt;em&gt;boolean&lt;/em&gt;&lt;/strong&gt; variable with a value of &lt;strong&gt;&lt;em&gt;false&lt;/em&gt;&lt;/strong&gt;, we can just return it. &lt;/p&gt;

&lt;p&gt;Thus far, we could write that out like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let canMakeNote = (source, note) =&amp;gt; {
    let boolean = false

    let cleanedSource = clean(source)
    let cleanedNote = clean(note)

    if (cleanedSource.length &amp;gt;= cleanedNote.length){
        use histogram to see if source contains all the letters needed to create note
    }
    return boolean
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is much closer to a working function than the pseudocode we started with, but there’s still a big vague chunk in the middle. &lt;/p&gt;

&lt;p&gt;That’s okay though, that’s what our &lt;strong&gt;&lt;em&gt;makeHistogram&lt;/em&gt;&lt;/strong&gt; function is for!&lt;/p&gt;

&lt;p&gt;We can call &lt;strong&gt;&lt;em&gt;makeHistogram&lt;/em&gt;&lt;/strong&gt; twice, inputting our &lt;strong&gt;&lt;em&gt;clean&lt;/em&gt;&lt;/strong&gt;ed arrays, and get two hash objects, which we can now compare.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let canMakeNote = (source, note) =&amp;gt; {
    let boolean = false

    let cleanedSource = clean(source)
    let cleanedNote = clean(note)

    if (cleanedSource.length &amp;gt;= cleanedNote.length){
        let sourceHistogram = makeHistogram(source)
        let noteHistogram = makeHistogram(cleanedNote)
        for(let letter in noteHistogram){
            if (the value of the key letter in sourceHistogram is greater than or equal to the value of the key letter in noteHistogram){
                boolean = true
            } else {
                boolean = false 
                break
            }
        }
    }
    return boolean
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There’s still a bit of pseudocode standing in, but we can now iterate through the keys of the cleaned &amp;amp; hashed note text, and check each one against the cleaned and hashed source text. As a hash key provides a specific place in memory to directly check, this is a very efficient way to compare these pieces of data. &lt;/p&gt;

&lt;p&gt;As we iterate through the note object, if the check against the source object reveals that it contains the correct character in the correct amounts, the boolean should be assigned the value &lt;strong&gt;&lt;em&gt;true&lt;/em&gt;&lt;/strong&gt;. If this check fails, the boolean should be assigned the value &lt;strong&gt;&lt;em&gt;false&lt;/em&gt;&lt;/strong&gt; and we can use the &lt;a href="https://www.w3schools.com/js/js_break.asp"&gt;***break&lt;/a&gt;*** statement to immediately exit the &lt;a href="https://www.w3schools.com/js/js_loop_for.asp"&gt;for loop&lt;/a&gt;, which will trigger the &lt;strong&gt;&lt;em&gt;boolean&lt;/em&gt;&lt;/strong&gt; return, thus causing our function to return false. &lt;/p&gt;

&lt;p&gt;However, if each character key checked returns true, the for loop will resolve with the &lt;strong&gt;&lt;em&gt;boolean&lt;/em&gt;&lt;/strong&gt; still assigned the value &lt;strong&gt;&lt;em&gt;true&lt;/em&gt;&lt;/strong&gt;, then and only then will our function return the value &lt;strong&gt;&lt;em&gt;true.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;All that’s left to do then is to write the code for testing the values of the hash objects. &lt;/p&gt;

&lt;p&gt;We need to check for two things: &lt;/p&gt;

&lt;p&gt;1: That the source hash object has a key matching the current letter.&lt;/p&gt;

&lt;p&gt;2: If true, that the corresponding value is greater than or equal to the value of corresponding to the current letter key in the note hash object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let canMakeNote = (source, note) =&amp;gt; {
    let boolean = false

    let cleanedSource = clean(source)
    let cleanedNote = clean(note)

    if (cleanedSource.length &amp;gt;= cleanedNote.length){
        let sourceHistogram = makeHistogram(source)
        let noteHistogram = makeHistogram(cleanedNote)
        for(let letter in noteHistogram){
            if (sourceHistogram[letter] &amp;amp;&amp;amp; sourceHistogram[letter] &amp;gt;= noteHistogram[letter]){
                boolean = true
            }else{
                boolean = false 
                break
            }
        }
    }
    return boolean
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Okay, this looks promising, let’s throw everything into the console and see what we get.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let quote = "Aut Viam Inveniam Aut Faciam"

let clean = (input) =&amp;gt; {
    return input.replace(/\s/g,'').toLowerCase().split("")
}

let makeHistogram = (input) =&amp;gt; {
    let histogram = {}

    for(let letter of input){
        letter in histogram ? histogram[letter] += 1 : histogram[letter] = 1
    }  
    return histogram
}

let canMakeNote = (source, note) =&amp;gt; {
    let boolean = false

    let cleanedSource = clean(source)
    let cleanedNote = clean(note)

    if (cleanedSource.length &amp;gt;= cleanedNote.length){
        let sourceHistogram = makeHistogram(source)
        let noteHistogram = makeHistogram(cleanedNote)
        for(let letter in noteHistogram){
            if (sourceHistogram[letter] &amp;amp;&amp;amp; sourceHistogram[letter] &amp;gt;= noteHistogram[letter]){
                boolean = true
            }else{
                boolean = false 
                break
            }
        }
    }
    return boolean
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;// let's try a word that only needs letters contained within our quote&lt;br&gt;
canMakeNote(quote, "acuminate")&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;true&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;// okay, now a word that requires one more letter "e" than our quote possesses&lt;br&gt;
canMakeNote(quote, "cuneate")&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;false&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;🌟 Great! &lt;/p&gt;

&lt;p&gt;I really love this algorithm challenge because I think it’s a perfect use case for one of my favorite algorithm-solving tools, the humble hash. I hope this solution illustrates how useful a hash table can be, and that this approach is helpful to all your algorithm-solving challenges!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>Find All Permutations of a String in Javascript</title>
      <dc:creator>noam sauer-utley</dc:creator>
      <pubDate>Fri, 14 Feb 2020 16:03:37 +0000</pubDate>
      <link>https://dev.to/noamsauerutley/find-all-permutations-of-a-string-in-javascript-6fl</link>
      <guid>https://dev.to/noamsauerutley/find-all-permutations-of-a-string-in-javascript-6fl</guid>
      <description>&lt;p&gt;Published by &lt;a href="https://levelup.gitconnected.com/"&gt;∞ Level Up Coding&lt;/a&gt;&lt;br&gt;
Featured by &lt;a href="https://medium.com/topic/javascript"&gt;★ Medium Curated&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--lf4aSTdS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2A8hi02sPoR-kuQ3O7AlBqCg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--lf4aSTdS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2A8hi02sPoR-kuQ3O7AlBqCg.png" alt="kitten with a ball of yellow yarn"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h4&gt;
  
  
  &lt;a href="https://github.com/noamsauerutley/string-permutations"&gt;GitHub repo with completed solution code and test suite.&lt;/a&gt;
&lt;/h4&gt;

&lt;blockquote&gt;
&lt;p&gt;Given a string, return all permutations of the string.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;When I sat down to solve this problem, I found it to be a great algorithm challenge. Why? While the task of manipulating a string may seem familiar on its surface, actually finding a complete solution requires us to handle some unexpected complexity, which provides the opportunity to utilize a &lt;a href="https://en.wikipedia.org/wiki/Recursive_tree"&gt;recursive tree&lt;/a&gt; and build a bit of familiarity with the &lt;a href="https://en.wikipedia.org/wiki/Master_theorem_%28analysis_of_algorithms%29"&gt;master theorem&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note&lt;/em&gt;&lt;/strong&gt;&lt;em&gt;: There is more than one way to solve this problem. The solution model I explore here utilizes tools and concepts that I find broadly valuable for the solution of&lt;/em&gt; &lt;a href="https://www.encyclopediaofmath.org/index.php/Algorithmic_problem"&gt;&lt;em&gt;algorithmic challenges&lt;/em&gt;&lt;/a&gt;&lt;em&gt;, and methods that I find intuitive for string manipulation within Javascript.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;First things first: What is a  &lt;a href="https://en.wikipedia.org/wiki/Permutation"&gt;&lt;strong&gt;permutation&lt;/strong&gt;&lt;/a&gt;?&lt;/p&gt;
&lt;h4&gt;
  
  
  per·mu·ta·tion
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://www.google.com/search?rlz=1C5CHFA_enUS709US712&amp;amp;sxsrf=ACYBGNTPndNyReUeZnT9AMXjhP4lKoxabw:1581528989144&amp;amp;q=how+to+pronounce+permutation&amp;amp;stick=H4sIAAAAAAAAAOMIfcRoyy3w8sc9YSmTSWtOXmPU4-INKMrPK81LzkwsyczPExLnYglJLcoV4pfi5eIuALJKS8ASVixKTKl5PItYZTLyyxVK8hUKgNrygfpSFZBUAQAUxHbOYQAAAA&amp;amp;pron_lang=en&amp;amp;pron_country=us&amp;amp;sa=X&amp;amp;ved=2ahUKEwj73uXMxsznAhVBmlkKHbHDBSkQ3eEDMAB6BAgFEAg"&gt;Learn to pronounce&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;noun&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;a way, especially one of several possible variations, in which a set or number of things can be ordered or arranged.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So every string has a number of permutations into which its characters could be re-arranged. A string permutation is similar to an &lt;a href="https://en.wikipedia.org/wiki/Anagram"&gt;anagram&lt;/a&gt;. However, it does not need to be an existing word, but can simply be a re-arrangement of the characters.&lt;/p&gt;

&lt;p&gt;An example of permutations of something other than a string would be this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--LtgtPzg9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AjpYcn_e_FDdczT4ZkeU5Xg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LtgtPzg9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AjpYcn_e_FDdczT4ZkeU5Xg.png" alt="red, green, and blue circles labeled 1, 2, &amp;amp; 3 arranged into 6 different ordered combinations or permutations."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For just three colors, we can have six different permutations, or ordered combinations of those colors.&lt;/p&gt;

&lt;p&gt;Another example of permutations would be a combination lock:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bRBjygSK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AdKlBQn44g7ZsW0eTu8nl-w.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bRBjygSK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AdKlBQn44g7ZsW0eTu8nl-w.jpeg" alt="Close up of the numbered wheels of a combination lock."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Uh-oh. The whole point of combination locks is that a relatively small amount of numbers can create a large enough number of ordered combinations to prohibit casual opening.&lt;/p&gt;

&lt;p&gt;Suddenly, this whole string-manipulation problem seems a bit more intimidating.&lt;/p&gt;

&lt;p&gt;So we’ve figured out what a permutation is, and established that (depending on the length of the string) we may be looking for a lot of them. Where to start?&lt;/p&gt;

&lt;p&gt;When I see a challenge like this, my first instinct is two do two things:&lt;/p&gt;

&lt;p&gt;1: Make an empty &lt;a href="https://en.wikipedia.org/wiki/Array_data_structure"&gt;array&lt;/a&gt;. If my final solution may return more than one “correct” element (in this case, permutations), I’ll need a place to store them before I return the complete solution.&lt;/p&gt;

&lt;p&gt;2: &lt;a href="https://en.wikipedia.org/wiki/Iteration"&gt;Iterate&lt;/a&gt;! If I need to find all the ordered combinations of characters in a string, creating a loop to iterate through all the characters in a string seems like a decent place to start.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let findPermutations = (string) =&amp;gt; {

  let permutationsArray = [] 

  for (let i = 0; i &amp;lt; string.length; i++){
    // do something
  }
  return permutationsArray
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Before we jump straight into our iteration, let’s knock a few things out of the way.&lt;/p&gt;

&lt;p&gt;What if the user enters an empty string, or an integer, or tries to run the function without entering anything at all? We can’t get all the permutations of a string if there’s no string.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let findPermutations = (string) =&amp;gt; {

   if (!string || typeof string !== "string"){
    return "Please enter a string"
  }

  let permutationsArray = [] 

  for (let i = 0; i &amp;lt; string.length; i++){
    // do something
  }
  return permutationsArray
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The new line of code will return an error message if the argument input into the function is &lt;a href="https://j11y.io/javascript/truthy-falsey/"&gt;falsey&lt;/a&gt;, or &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof"&gt;if it is not a string&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Okay, great!&lt;/p&gt;

&lt;p&gt;But what if the string is really short? Like only-one-character short? That’s also a scenario where we don’t really need to mess with the whole iterating and pushing things into an array bit. If our string is, for example, just “a”, it only has one permutation — “a”. We can just return “a”.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let findPermutations = (string) =&amp;gt; {

   if (!string || typeof string !== "string"){
    return "Please enter a string"
  } else if (string.length &amp;lt; 2 ){
    return string
  }

  let permutationsArray = [] 

  for (let i = 0; i &amp;lt; string.length; i++){
    // do something
  }
  return permutationsArray
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Alright, now that’s out of the way, we can get back to our iterative loop.&lt;/p&gt;

&lt;p&gt;The structure of our function in its current state now looks a bit similar to something called the master theorem.&lt;/p&gt;

&lt;h4&gt;
  
  
  The Master Theorem
&lt;/h4&gt;

&lt;p&gt;What is the &lt;a href="https://medium.com/@malaynandasana/master-theorem-b544fa8829f7"&gt;master theorem&lt;/a&gt;?&lt;/p&gt;

&lt;p&gt;It is a set of steps for breaking down potentially complex challenges into a set of smaller problems. Many problems or technical challenges fall into the category of &lt;a href="https://en.wikipedia.org/wiki/Divide-and-conquer_algorithm"&gt;Divide and Conquer Algorithms&lt;/a&gt;, which require the would-be solver to break a piece of data down into smaller pieces until the pieces are simple enough to be solved directly.&lt;/p&gt;

&lt;p&gt;Written out in pseudocode, it looks like this:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;procedure&lt;/strong&gt; p( input &lt;em&gt;x&lt;/em&gt; of size &lt;em&gt;n&lt;/em&gt; ):&lt;br&gt;&lt;br&gt;
   &lt;strong&gt;if&lt;/strong&gt; &lt;em&gt;n&lt;/em&gt; &amp;lt; some constant &lt;em&gt;k&lt;/em&gt;:&lt;br&gt;&lt;br&gt;
     Solve &lt;em&gt;x&lt;/em&gt; directly without recursion&lt;br&gt;&lt;br&gt;
   &lt;strong&gt;else&lt;/strong&gt;:&lt;br&gt;&lt;br&gt;
     Create &lt;em&gt;a&lt;/em&gt; subproblems of &lt;em&gt;x&lt;/em&gt;, each having size &lt;em&gt;n&lt;/em&gt;/&lt;em&gt;b&lt;/em&gt;&lt;br&gt;&lt;br&gt;
     Call procedure p recursively on each subproblem&lt;br&gt;&lt;br&gt;
     Combine the results from the subproblems&lt;/p&gt;

&lt;p&gt;A few important things happen here:&lt;/p&gt;

&lt;p&gt;1: a conditional checks if the size of the input is smaller than a constant.&lt;/p&gt;

&lt;p&gt;2: if the input is larger than said constant, the input is broken down into smaller pieces until they are all small enough to run the &lt;strong&gt;procedure&lt;/strong&gt; on directly&lt;/p&gt;

&lt;p&gt;3: when this is done, the results of all the pieces post-procedure can be combined and returned as a single large bit of data.&lt;/p&gt;

&lt;p&gt;This approach to breaking down problems is often visualized as a tree (especially as this is often helpful for establishing down a problem’s &lt;a href="https://www.geeksforgeeks.org/understanding-time-complexity-simple-examples/"&gt;time complexity&lt;/a&gt;. You can read more about time complexity and the master method &lt;a href="https://medium.com/@aman.jain/demystifying-master-theorem-e0436b2aff1f"&gt;here&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--wzu0eclR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2A3K1-xsPyGVwhSXstZoxtug.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--wzu0eclR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2A3K1-xsPyGVwhSXstZoxtug.png" alt="five iterations of a recursive tree"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Want to read more about recursive trees and the master theorem? &lt;a href="https://www.cs.cornell.edu/courses/cs3110/2012sp/lectures/lec20-master/lec20.html"&gt;I like this synopsis from Cornell&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Note how similar this structure is to the following diagram of our specific challenge of finding all permutations of a string:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s---zfTstJd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AQBEePGu2SigGcbMeMqwTbA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---zfTstJd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AQBEePGu2SigGcbMeMqwTbA.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;While our current function isn’t exactly the same as the abstracted pseudocode of our master theorem, we have established the logical path of returning one solution if our input is smaller than a constant (in our case, if &lt;strong&gt;string.length&lt;/strong&gt; is less than &lt;strong&gt;2&lt;/strong&gt;), and if not, creating a list of subproblems to solve.&lt;/p&gt;

&lt;p&gt;If you’ve flattened out nested arrays before, this approach may feel familiar. It’s can be a good starting point for a wide variety of challenges — it won’t be the relevant method for every problem, but provides a nice place to start.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: This approach does utilize&lt;/em&gt; &lt;a href="https://en.wikipedia.org/wiki/Recursion"&gt;&lt;strong&gt;&lt;em&gt;recursion&lt;/em&gt;&lt;/strong&gt;&lt;/a&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--A52Dug6H--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AX_6FLmHpf2wr897tIqcj5Q.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--A52Dug6H--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AX_6FLmHpf2wr897tIqcj5Q.jpeg" alt="urbandictionary.com for recursion; the definition reads “See recursion”."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can read more about &lt;strong&gt;recursion&lt;/strong&gt; &lt;a href="https://www.freecodecamp.org/news/recursion-demystified-99a2105cb871/"&gt;here&lt;/a&gt;, &lt;a href="https://medium.com/code-zen/recursion-demystified-24867f045c62"&gt;here&lt;/a&gt; (code examples in &lt;a href="https://en.wikipedia.org/wiki/JavaScript"&gt;javascript&lt;/a&gt;), &lt;a href="https://medium.com/@daniel.oliver.king/getting-started-with-recursion-f89f57c5b60e"&gt;here&lt;/a&gt; (code examples in &lt;a href="https://en.wikipedia.org/wiki/JavaScript"&gt;javascript&lt;/a&gt;), &lt;a href="https://medium.com/better-programming/understanding-recursion-recursively-181f5f4dc528"&gt;here&lt;/a&gt; (code examples in &lt;a href="https://en.wikipedia.org/wiki/Ruby_%28programming_language%29"&gt;ruby&lt;/a&gt;), and &lt;a href="https://medium.com/@isaac_70614/recursion-a-step-by-step-introduction-ed25c957559c"&gt;here&lt;/a&gt; (code examples in &lt;a href="https://en.wikipedia.org/wiki/Python_%28programming_language%29"&gt;python&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Okay, back to our code.&lt;/p&gt;

&lt;p&gt;Now, if we want to utilize the master theorem approach, we can update our plan to something a bit more clear than &lt;code&gt;// do something&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let findPermutations = (string) =&amp;gt; {

   if (!string || typeof string !== "string"){
    return "Please enter a string"
  } else if (string.length &amp;lt; 2 ){
    return string
  }

  let permutationsArray = [] 

  for (let i = 0; i &amp;lt; string.length; i++){
    // Create a subproblems of string, each having size n/b
    // Call procedure p recursively on each subproblem
    // Combine the results from the subproblems
  }
  return permutationsArray
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;For ease, I’d like to assign the current element we’re iterating over to the variable &lt;strong&gt;char&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;So the first thing we’re supposed to do is break our &lt;strong&gt;string&lt;/strong&gt; down into sub-problems.&lt;/p&gt;

&lt;p&gt;To start, we have our current character, aka &lt;strong&gt;string[i]&lt;/strong&gt;, aka &lt;strong&gt;char&lt;/strong&gt;. To begin breaking down the rest of the &lt;strong&gt;string&lt;/strong&gt;, we need to collect the remaining characters.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let findPermutations = (string) =&amp;gt; {

   if (!string || typeof string !== "string"){
    return "Please enter a string"
  } else if (string.length &amp;lt; 2 ){
    return string
  }

  let permutationsArray = [] 

  for (let i = 0; i &amp;lt; string.length; i++){
    let char = string[i]
    let remainingChars = string.slice(0, i) + string.slice(i + 1, string.length)

    // Call procedure p recursively on each subproblem
    // Combine the results from the subproblems
  }
  return permutationsArray
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Just as we assigned our current character to the variable &lt;strong&gt;char&lt;/strong&gt;, let’s assign the remaining characters to the variable &lt;strong&gt;remainingChars&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note&lt;/em&gt;&lt;/strong&gt;&lt;em&gt;: There are many different ways one might collect the&lt;/em&gt; &lt;strong&gt;remainingChars&lt;/strong&gt;&lt;em&gt;. This is just one method.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;To collect those characters, we can use the string method &lt;a href="https://www.w3schools.com/jsref/jsref_slice_string.asp"&gt;slice&lt;/a&gt;. &lt;a href="https://www.w3schools.com/jsref/jsref_substring.asp"&gt;Substring&lt;/a&gt; is a similar method, so if you’re more familiar with that, you can use it instead. Slice is &lt;a href="https://medium.com/@coadams9/javascript-a-few-methods-and-destructive-vs-non-destructive-c20197534ad1"&gt;non-destructive&lt;/a&gt;, so we don’t need to worry about mutating our original string — the result we get by slicing our string will be its own new string.&lt;/p&gt;

&lt;p&gt;So we’ll slice the characters from index &lt;strong&gt;0&lt;/strong&gt; (the first character in the string) to index &lt;strong&gt;i&lt;/strong&gt; (our current character, &lt;strong&gt;char&lt;/strong&gt;). Then, we’ll join the characters from index &lt;strong&gt;i + 1&lt;/strong&gt; (the next character after &lt;strong&gt;char&lt;/strong&gt;) to index &lt;strong&gt;string.length&lt;/strong&gt; (the last character in &lt;strong&gt;string&lt;/strong&gt;).&lt;/p&gt;

&lt;p&gt;So now we have two smaller strings — &lt;strong&gt;char&lt;/strong&gt; and &lt;strong&gt;remainingChars&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;What now?&lt;/p&gt;

&lt;p&gt;Well, let’s consult the master theorem:&lt;/p&gt;

&lt;p&gt;Call procedure p recursively on each subproblem&lt;/p&gt;

&lt;p&gt;So we’re going to call our &lt;strong&gt;findPermutations&lt;/strong&gt; function on our &lt;strong&gt;remainingChars&lt;/strong&gt; string.&lt;/p&gt;

&lt;p&gt;Then what?&lt;/p&gt;

&lt;p&gt;Combine the results from the subproblems&lt;/p&gt;

&lt;p&gt;I knew we’d need that empty array.&lt;/p&gt;

&lt;p&gt;Okay, so what does this look like in JavaScript?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let findPermutations = (string) =&amp;gt; {
  if (!string || typeof string !== "string"){
    return "Please enter a string"
  } else if (string.length &amp;lt; 2 ){
    return string
  }

  let permutationsArray = [] 

  for (let i = 0; i &amp;lt; string.length; i++){
    let char = string[i]

    let remainingChars = string.slice(0, i) + string.slice(i + 1, string.length)

    for (let permutation of findPermutations(remainingChars)){
      permutationsArray.push(char + permutation) }
  }
  return permutationsArray
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;So we’ve done a few things here.&lt;/p&gt;

&lt;p&gt;We recursively called &lt;strong&gt;findPermutations&lt;/strong&gt; on &lt;strong&gt;remainingChars&lt;/strong&gt;. For each result of that function, which I assigned to a variable named &lt;strong&gt;permutation&lt;/strong&gt;, we can push a string that is the combination of &lt;strong&gt;char&lt;/strong&gt; and &lt;strong&gt;permutation&lt;/strong&gt; into our &lt;strong&gt;permutationsArray&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;findPermutations("abc")

(6) ["abc", "acb", "bac", "bca", "cab", "cba"]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;So let’s see what we get when we return &lt;strong&gt;permutationsArray&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Okay, great! When given the input &lt;strong&gt;“abc”&lt;/strong&gt;, our &lt;strong&gt;findPermutations&lt;/strong&gt; function returns all six permutations!&lt;/p&gt;

&lt;p&gt;Let me try one more thing though.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;findPermutations("aabc")

(24) ["aabc", "aacb", "abac", "abca", "acab", "acba", "aabc", "aacb", "abac", "abca", "acab", "acba", "baac", "baca", "baac", "baca", "bcaa", "bcaa", "caab", "caba", "caab", "caba", "cbaa", "cbaa"]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Well, that’s not good. If a character in our string repeats, we get each permutation twice. Lots of strings have repeating characters.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let findPermutations = (string) =&amp;gt; {
  if (!string || typeof string !== "string"){
    return "Please enter a string"
  } else if (string.length &amp;lt; 2 ){
    return string
  }

  let permutationsArray = [] 

  for (let i = 0; i &amp;lt; string.length; i++){
    let char = string[i]

    if (string.indexOf(char) != i)
    continue

    let remainingChars = string.slice(0, i) + string.slice(i + 1, string.length)

    for (let permutation of findPermutations(remainingChars)){
      permutationsArray.push(char + permutation) }
  }
  return permutationsArray
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;There are a lot of different ways to remove superfluous elements, but I chose to use Javascript’s &lt;a href="https://www.w3schools.com/jsref/jsref_indexof.asp"&gt;indexOf&lt;/a&gt; method to identify if the current character has already been run through our &lt;strong&gt;findPermutations&lt;/strong&gt; method. indexOf returns the &lt;strong&gt;first&lt;/strong&gt; index of a character, so if we’ve already run &lt;strong&gt;findPermutations&lt;/strong&gt; for an “a”, for example, the indexOf(“a”) will be different than the index of &lt;strong&gt;char&lt;/strong&gt;, the current, later “a”.&lt;/p&gt;

&lt;p&gt;If this is true, we can &lt;a href="https://www.w3schools.com/js/js_break.asp"&gt;&lt;strong&gt;continue&lt;/strong&gt;&lt;/a&gt;, which will essentially skip the current iterative loop and move on to the next.&lt;/p&gt;

&lt;p&gt;Let’s run &lt;strong&gt;findPermutation&lt;/strong&gt; with this addition.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;findPermutations("aabc")

(12) ["aabc", "aacb", "abac", "abca", "acab", "acba", "baac", "baca", "bcaa", "caab", "caba", "cbaa"]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Perfect! 🌟 A master theorem based approach allowed us to quickly break this problem down into bite sized pieces and begin returning correct results, leaving only a few tweaks needed here and there to deliver our solution in exactly the desired format.&lt;/p&gt;

&lt;h4&gt;
  
  
  Review:
&lt;/h4&gt;

&lt;p&gt;So what was our master theorem based approach again?&lt;/p&gt;

&lt;p&gt;1: Establish a base case — if our input’s size is less than a certain constant, solve it directly without recursion.&lt;/p&gt;

&lt;p&gt;2: If the input is bigger than said constant, break it down into smaller pieces.&lt;/p&gt;

&lt;p&gt;3: Call the function recursively on the pieces, until they are small enough to be solved directly.&lt;/p&gt;

&lt;p&gt;4: Combine the results from the pieces, and return the completed solution.&lt;/p&gt;

&lt;p&gt;I have found this model to be a really handy tool that reliably provides me with a place to start when tackling algorithmic challenges. While not specifically applicable to every algorithm problem, and not always the most performant or elegant solution, it’s a reliable workhorse model that can serve you well!&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://github.com/noamsauerutley/string-permutations"&gt;GitHub repo containing the solution code&lt;/a&gt; also comes with a test suite, so you can practice or play around with finding alternate solutions for this problem if you like.&lt;/p&gt;

&lt;p&gt;If you want to explore further, you could try using the solution model utilized above to find all the combinations of a combination lock? Does it work? Do you need to make any changes?&lt;/p&gt;

</description>
      <category>algorithms</category>
      <category>mastertheorem</category>
      <category>javascript</category>
      <category>recursion</category>
    </item>
    <item>
      <title>Solving The Two-Sum Problem in Javascript, Three Ways</title>
      <dc:creator>noam sauer-utley</dc:creator>
      <pubDate>Fri, 14 Feb 2020 15:22:08 +0000</pubDate>
      <link>https://dev.to/noamsauerutley/solving-the-two-sum-problem-in-javascript-three-ways-43lf</link>
      <guid>https://dev.to/noamsauerutley/solving-the-two-sum-problem-in-javascript-three-ways-43lf</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Ue9F99_v--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AWw_kGxT_HRoNzbDGEZ03Yw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Ue9F99_v--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AWw_kGxT_HRoNzbDGEZ03Yw.png" alt="Two Sum Problem [2, 4, 7, 8, 9] 11"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Published by &lt;a href="https://levelup.gitconnected.com/"&gt;∞ Level Up Coding&lt;/a&gt;&lt;br&gt;
Featured by &lt;a href="https://medium.com/topic/javascript"&gt;★ Medium Curated&lt;/a&gt;&lt;/p&gt;
&lt;h4&gt;
  
  
  &lt;a href="https://github.com/noamsauerutley/two-sum"&gt;This Github repo contains my completed code for all three solution models.&lt;/a&gt;
&lt;/h4&gt;

&lt;p&gt;What is the Two-Sum Problem?&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;“Given an array of integers and a target number, return the two integers that add up to the target number”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--kRb8YNja--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AE7Wk4TgNPZaswlccsIp2Fw.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kRb8YNja--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AE7Wk4TgNPZaswlccsIp2Fw.jpeg" alt="x + y = result"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h4&gt;
  
  
  &lt;strong&gt;Notes:&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;&lt;em&gt;The desired result can be returned in a few different forms — I’ve seen queries ask either for the&lt;/em&gt; &lt;a href="https://en.wikipedia.org/wiki/Array_data_structure"&gt;&lt;em&gt;indices&lt;/em&gt;&lt;/a&gt; &lt;em&gt;of the&lt;/em&gt; &lt;a href="https://www.mathsisfun.com/definitions/addend.html"&gt;&lt;em&gt;addends&lt;/em&gt;&lt;/a&gt; &lt;em&gt;(aka their locations in the array), or for the addends themselves.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Additionally, some challenges are structured so that only one pair of numbers will add up to the sum.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;In my solutions, I will be returning&lt;/em&gt; &lt;strong&gt;&lt;em&gt;all discrete successful addend pairs&lt;/em&gt;&lt;/strong&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I will briefly address approaches for adapting my solutions to return a&lt;/em&gt; &lt;strong&gt;&lt;em&gt;single addend pair&lt;/em&gt;&lt;/strong&gt; &lt;em&gt;or&lt;/em&gt; &lt;strong&gt;&lt;em&gt;array indices rather than addends themselves.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I will use the &lt;strong&gt;array [2, 3, 4, 3, 6, 7]&lt;/strong&gt;, and the &lt;strong&gt;sum integer 6&lt;/strong&gt; to test all solutions.&lt;/p&gt;
&lt;h3&gt;
  
  
  1: BRUTE FORCE
&lt;/h3&gt;

&lt;p&gt;For my first solution, I’m not prioritizing elegance or performance, merely attempting to hack a working solution. Once I have some working raw material and an initial understanding of the mechanics of finding my desired numbers, then I can play with my solution to address &lt;a href="https://www.geeksforgeeks.org/understanding-time-complexity-simple-examples/"&gt;time complexity&lt;/a&gt;, etc.&lt;/p&gt;

&lt;p&gt;As I know I may need to find multiple correct number combinations, I start with an empty array, and plan to pass my successful number combos into it, then return the array of number combos.&lt;/p&gt;

&lt;p&gt;If it were established at the beginning of a challenge that each sum + array combo could only have one successful solution, I could skip this step and instead return the correct addends once found.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let bruteForceTwoSum = (array, sum) =&amp;gt; {

  let nums = []

  // find addends
  // pass them into nums array for storage

   return nums
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;First, I need to find the successful combos.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let bruteForceTwoSum = (array, sum) =&amp;gt; {

  let nums = []

      for(let x in array){
        for(let y in array){
            // see if array[x] + array[y] === sum
            // save successful combos to nums array
        }
      }     
   return nums
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;I start by creating two loops, allowing me to iterate through every combination of numbers in the array. Now I can test the combos to see if any of them add up to &lt;strong&gt;&lt;em&gt;sum&lt;/em&gt;&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let bruteForceTwoSum = (array, sum) =&amp;gt; {

  let nums = []

      for(let x in array){
        for(let y in array){

          if (array[x] + array[y] === sum){
            nums.push([array[x], array[y]])
          }

        }
      }     
   return nums
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;If they do, I want to save them in my container array, which I’ll return after closing out my loops.&lt;/p&gt;

&lt;p&gt;If I wanted the &lt;strong&gt;&lt;em&gt;indices&lt;/em&gt;&lt;/strong&gt; instead of the &lt;strong&gt;&lt;em&gt;number elements&lt;/em&gt;&lt;/strong&gt; themselves, I could instead push &lt;strong&gt;&lt;em&gt;x&lt;/em&gt;&lt;/strong&gt; &amp;amp; &lt;strong&gt;&lt;em&gt;y&lt;/em&gt;&lt;/strong&gt; to the &lt;strong&gt;&lt;em&gt;nums&lt;/em&gt;&lt;/strong&gt; array.&lt;/p&gt;

&lt;p&gt;When run in the console, this function returns:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let array = [2, 3, 4, 3, 6, 7]
let sum = 6

bruteForceTwoSum(array, sum)
0: (2) [2, 4]
1: (2) [3, 3]
2: (2) [3, 3]
3: (2) [4, 2]
4: (2) [3, 3]
5: (2) [3, 3]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;✔️ This function is finding and returning both [2, 4] and [3, 3].&lt;/p&gt;

&lt;p&gt;✖️ It’s also returning them multiple times each. Not what we want.&lt;/p&gt;

&lt;p&gt;I could try to check the nums array before pushing new number combos in, but the nested array format I’ve used makes this a hassle.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: It is perfectly reasonable to check nums.flat(Infinite) for the current elements, but I chose a slightly less computationally expensive option.&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function bruteForceTwoSum(array, sum){
    let nums = []

    let prevNums = []

    for(let x in array){
        for(let y in array){
            if (array[x] + array[y] === sum){
                if(!!nums.length){ 
                    if (!prevNums.includes(array[x]) &amp;amp;&amp;amp; !prevNums.includes(array[y])) {
                        prevNums.push(array[x])
                        nums.push([array[x], array[y]])
                    } 
                } else {
                    nums.push([array[x], array[y]])
                    prevNums.push(array[x])
                }
            }
        }
    }
   return nums
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;I’ve added an additional array &lt;strong&gt;&lt;em&gt;prevNums&lt;/em&gt;&lt;/strong&gt; for the sole purpose of storing found numbers, and can now check if a number has already been found &amp;amp; added before pushing it into &lt;strong&gt;&lt;em&gt;nums&lt;/em&gt;&lt;/strong&gt;. I only do this if &lt;strong&gt;&lt;em&gt;nums&lt;/em&gt;&lt;/strong&gt; is not empty.&lt;/p&gt;

&lt;p&gt;What does this return?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let array = [2, 3, 4, 3, 6, 7]
let sum = 6
bruteForceTwoSum(array, sum)

0: (2) [2, 4]
1: (2) [3, 3]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Great! This is exactly the result I want. 🌟&lt;/p&gt;

&lt;h3&gt;
  
  
  2: BINARY SEARCH
&lt;/h3&gt;

&lt;p&gt;Okay, so I have my first layer. I can find the combinations in an array that add up to a given sum, and return them in a clean, readable, non-redundant format.&lt;/p&gt;

&lt;p&gt;However, what if my array were not &lt;strong&gt;[2, 3, 4, 3, 6, 7]&lt;/strong&gt;, but an array of thousands of numbers. Maybe even tens of thousands? Based on my first solution model, I’d have to iterate through endless combinations of numbers, even if my sum was still only &lt;strong&gt;6&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;That’s a huge waste of computing energy.&lt;/p&gt;

&lt;p&gt;I’m not going to get too deeply into the concept of &lt;a href="https://www.geeksforgeeks.org/understanding-time-complexity-simple-examples/"&gt;time complexity&lt;/a&gt; here, but I want to find a solution that will scale up better than my initial brute force model, due to requiring fewer computations.&lt;/p&gt;

&lt;p&gt;In order to do that, I’m going to use a &lt;a href="https://www.computerhope.com/jargon/b/binary-search.htm"&gt;binary search&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I’m going to write a helper function to perform the binary search itself, then a second function that will utilize it to find the the correct addends for our given sum.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let binarySearch = (array, target, start=0, end=array.length-1) =&amp;gt; {}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;I’ll pass four &lt;a href="https://www.javascripttutorial.net/es6/javascript-default-parameters/"&gt;parameters&lt;/a&gt; into the &lt;strong&gt;&lt;em&gt;binarySearch&lt;/em&gt;&lt;/strong&gt; helper function:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;&lt;em&gt;array&lt;/em&gt;&lt;/strong&gt;:  This is the same array we’ve been iterating through. However, any array passed into this function will need to be sorted low to high in order for this function to work!&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;&lt;em&gt;target&lt;/em&gt;&lt;/strong&gt;: This is the number we’re looking for — when applied in the &lt;strong&gt;&lt;em&gt;twoSum&lt;/em&gt;&lt;/strong&gt; solution, this will be the &lt;strong&gt;&lt;em&gt;second addend&lt;/em&gt;&lt;/strong&gt; in a pair.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;&lt;em&gt;start&lt;/em&gt;&lt;/strong&gt;: The index at which we start iterating.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;&lt;em&gt;end&lt;/em&gt;&lt;/strong&gt;: The index at which we stop iterating.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;First things first, I want to find the middle of the array. If it contains an even number of elements, I’ll need to round down.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let binarySearch = (array, target, start=0, end=array.length-1) =&amp;gt; {
    let midPoint = ~~(start + (end - start)/2)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;I’m using the&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;(start + (end — start)/2)&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;method to get the midpoint so as to avoid some potential edge case errors as explained &lt;a href="https://www.geeksforgeeks.org/start-end-start2-preferrable-method-calculating-middle-array-start-end2/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I want to round the midpoint down to the nearest integer. I could use&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;Math.floor(start + (end — start)/2)&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;to handle my rounding, but the &lt;a href="http://rocha.la/JavaScript-bitwise-operators-in-practice"&gt;bitwise&lt;/a&gt; operator &lt;strong&gt;&lt;em&gt;~~&lt;/em&gt;&lt;/strong&gt; can do the same job of rounding down to the nearest integer a bit more &lt;a href="//%20https://blog.blakesimpson.co.uk/page.php?id=58&amp;amp;title=fastest-alternative-to-math-floor-in-javascript"&gt;quickly&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Since I’m going to be testing for several different cases in this function, I’m going to use a &lt;a href="https://www.w3schools.com/js/js_switch.asp"&gt;switch statement&lt;/a&gt; instead of an &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else"&gt;if/else statement&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let binarySearch = (array, target, start=0, end=array.length-1) =&amp;gt; {
    let midPoint = ~~(start + (end - start)/2)

    switch(true){
        case array[start] === target:
            return array[start]
        case array[midPoint] === target:
            return array[midPoint]
        case array[end] === target:
            return array[end]
        case end - start === 0:
            return false 
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;As I’m trying to make this approach a bit more efficient, I’m starting with a few cases that have relatively &lt;a href="https://yourbasic.org/algorithms/time-complexity-explained/"&gt;low time complexity cost&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I check for the cases where:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  1: The first number is the target number.&lt;/li&gt;
&lt;li&gt;  2: The middle number is the target number.&lt;/li&gt;
&lt;li&gt;  3: The last number is the target number.&lt;/li&gt;
&lt;li&gt;  4: The array or array section through which I want to iterate is empty.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If none of these cases are true, I can move on to the iterating.&lt;/p&gt;

&lt;p&gt;To do so, I’ll add two more cases:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let binarySearch = (array, target, start=0, end=array.length-1) =&amp;gt; {
    let midPoint = ~~(start + (end - start)/2)

    switch(true){
        case array[start] === target:
            return array[start]
        case array[midPoint] === target:
            return array[midPoint]
        case array[end] === target:
            return array[end]
        case end - start === 0:
            return false
        case array[midPoint] &amp;gt; target:
            return binarySearch(array, target, start+1, midPoint-1)
        case array[midPoint] &amp;lt; target:
            return binarySearch(array, target, midPoint+1, end-1)    
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;If the middle number is bigger than the target, I know that our target number is somewhere between &lt;strong&gt;&lt;em&gt;array[start]&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;array[midpoint]&lt;/em&gt;&lt;/strong&gt;. Therefore, I &lt;a href="https://www.geeksforgeeks.org/recursion/"&gt;recursively&lt;/a&gt; call our &lt;strong&gt;&lt;em&gt;binarySearch&lt;/em&gt;&lt;/strong&gt; function on a new set of numbers, which will be only the elements between &lt;strong&gt;&lt;em&gt;array[start]&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;array[midpoint]&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Additionally, as we’ve already checked &lt;strong&gt;&lt;em&gt;array[start]&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;array[midpoint]&lt;/em&gt;&lt;/strong&gt; against to see if either matches our target number in our initial cases, we can exclude those from our list, leaving only the elements between &lt;strong&gt;&lt;em&gt;array[start+1]&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;array[midpoint-1]&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This will find a new start, end, and midpoint, and repeat the function on the now-halved collection of elements.&lt;/p&gt;

&lt;p&gt;The last case is for if the middle number is smaller than the target number. In this case, we recursively call &lt;strong&gt;&lt;em&gt;binarySearch&lt;/em&gt;&lt;/strong&gt; on the collection of elements between &lt;strong&gt;&lt;em&gt;array[midpoint+1]&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;array[end-1]&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The logic to this is similar to the previous case — if the target number is greater than the midpoint in a sorted array, we can be confident that it won’t be in the first half, and can skip iterating through those, only looking in the second half of the array (minus the midpoint and end, which we’ve already checked for a match).&lt;/p&gt;

&lt;p&gt;Using this recursive approach, we can find the desired number in an array by repeatedly halving the array, thus performing &lt;a href="https://stackoverflow.com/questions/8185079/how-to-calculate-binary-search-complexity"&gt;significantly fewer calculations&lt;/a&gt; than we would were we to iterate through an entire array every time we wanted to see if it contained a single element.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let binarySearch = (array, target, start=0, end=array.length-1) =&amp;gt; {

    let midPoint = ~~(start + (end - start)/2)

    switch(true){
        case array[start] === target:
            return array[start]
        case array[midPoint] === target:
            return array[midPoint]
        case array[end] === target:
            return array[end]
        case end - start === 0:
            return false
        case array[midPoint] &amp;gt; target:
            return binarySearch(array, target, start+1, midPoint-1)
        case array[midPoint] &amp;lt; target:
            return binarySearch(array, target, midPoint+1, end-1)    
    }
    return false
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Finally, I’ve added a return statement which allows this function to return false if the desired value is not present.&lt;/p&gt;

&lt;p&gt;If this function works as desired, it will repeat until it either finds and returns the desired element or returns false, if the element is not present in the given array. Thus, the &lt;a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Return_values"&gt;return value&lt;/a&gt; of the &lt;strong&gt;&lt;em&gt;binarySearch&lt;/em&gt;&lt;/strong&gt; function is either &lt;strong&gt;the desired element&lt;/strong&gt; if it is present or &lt;strong&gt;false&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let array = [2, 3, 4, 3, 6, 7]

binarySearch(array, 9)
&amp;gt; false

binarySearch(array, 4)
&amp;gt; 4
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Great! Now we have our working helper method 🌟&lt;/p&gt;

&lt;p&gt;How do we apply this to our two-sum problem though?&lt;/p&gt;

&lt;p&gt;We know that we need to start with a sorted array in order to use a binary search, so we’ll begin by sorting our initial array.&lt;/p&gt;

&lt;p&gt;Then, we can set up the same basic structures we used previously, by creating two empty arrays: one for storing nested arrays containing our successful combinations of addends, and another for storing the elements in those combinations on the accessible top layer for later checking.&lt;/p&gt;

&lt;p&gt;We’ll want to find all those combinations of elements, store them in our &lt;strong&gt;&lt;em&gt;nums&lt;/em&gt;&lt;/strong&gt; array, then return that array at the end, just like last time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
let binarySearchTwoSum = (array, sum) =&amp;gt; {
    let sortedArray = array.sort()

    let nums = []
    let prevNums = []

    // find our number combos that add up to sum
    // check to see if we've already found them
    // if not, add them to nums

    return nums
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This time, however, we won’t be creating nested loops to iterate through.&lt;/p&gt;

&lt;p&gt;This time, we’re only iterating through our array once.&lt;/p&gt;

&lt;p&gt;For each element, the value &lt;strong&gt;&lt;em&gt;addend&lt;/em&gt;&lt;/strong&gt; will be assigned to the number that would equal &lt;strong&gt;&lt;em&gt;sum&lt;/em&gt;&lt;/strong&gt; minus the element.&lt;/p&gt;

&lt;p&gt;So, for a sum of &lt;strong&gt;&lt;em&gt;6&lt;/em&gt;&lt;/strong&gt; and an element of &lt;strong&gt;&lt;em&gt;2&lt;/em&gt;&lt;/strong&gt;, addend would be the integer &lt;strong&gt;&lt;em&gt;4&lt;/em&gt;&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let binarySearchTwoSum = (array, sum) =&amp;gt; {
    let sortedArray = array.sort()

    let nums = []
    let prevNums = []

    for (let i in sortedArray){
      // if sortedArray includes sum minus sortedArray[i], find it
      // push sortedArray[i] and the found number into nums
      // make sure no redundant numbers are pushed
    }
    return nums
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;That gives us a target integer, which is exactly what our &lt;strong&gt;&lt;em&gt;binarySearch&lt;/em&gt;&lt;/strong&gt; function needs.&lt;/p&gt;

&lt;p&gt;So this time, we’ll use the &lt;strong&gt;&lt;em&gt;binarySearch&lt;/em&gt;&lt;/strong&gt; helper function to do the work for us.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
let binarySearchTwoSum = (array, sum) =&amp;gt; {
    let sortedArray = array.sort()

    let nums = []
    let prevNums = []

    for (let i in sortedArray){
        let addend = binarySearch(sortedArray, sum-sortedArray[i])
        if (!!addend &amp;amp;&amp;amp; !prevNums.includes(array[i]) &amp;amp;&amp;amp; !prevNums.includes(addend)){
            nums.push([sortedArray[i], addend])
            prevNums.push(addend)
        }
    }
    return nums
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This way, instead of nesting iterators, we find what the second number in any given combo would be, then use the more efficient binary search method to see if that number is anywhere in our array.&lt;/p&gt;

&lt;p&gt;Just as we did previously, we can use the &lt;strong&gt;&lt;em&gt;prevNum&lt;/em&gt;&lt;/strong&gt; array as a vehicle to store and check for previously found solutions, so we aren’t returning redundant combinations.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let array = [2, 3, 4, 3, 6, 7]
let sum = 6

binarySearchTwoSum(array, 6)

0: (2) [2, 4]
1: (2) [3, 3]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Great! This also returns our desired result 🌟&lt;/p&gt;

&lt;h3&gt;
  
  
  3: HASH
&lt;/h3&gt;

&lt;p&gt;Using a binary search made our last solution more efficient than the brute force nested loops solution, but is it possible to improve even more?&lt;/p&gt;

&lt;p&gt;There’s another tool available to help us efficiently check whether or now our desired addend exists in our array: a &lt;a href="https://medium.com/javascript-in-plain-english/algorithm-in-javascript-hash-table-7b0464d2b81b"&gt;hash table&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
let hashTwoSum = (array, sum) =&amp;gt; {
    let storageHash = {}
    let nums = []

    for(let i in array){
      // for each array element, find its addend
      // see if addend is in array
      // if so
      // push array element and addend to nums
    }
    return nums
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This time, we’re starting with an empty &lt;a href="https://javascript.info/object"&gt;object&lt;/a&gt;, &lt;strong&gt;&lt;em&gt;storageHash&lt;/em&gt;&lt;/strong&gt;, in addition to our empty &lt;strong&gt;&lt;em&gt;nums&lt;/em&gt;&lt;/strong&gt; array.&lt;/p&gt;

&lt;p&gt;Just as we did previously, we want to iterate through our array, and find the remainder of &lt;strong&gt;&lt;em&gt;sum&lt;/em&gt;&lt;/strong&gt; minus each element. Then, we want to see if that remainder exists in &lt;strong&gt;&lt;em&gt;array&lt;/em&gt;&lt;/strong&gt;. If it does, we’ll push both the remainder and the element into the &lt;strong&gt;&lt;em&gt;nums&lt;/em&gt;&lt;/strong&gt; array, which we’ll eventually return after our loop resolves.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
let hashTwoSum = (array, sum) =&amp;gt; {
    let storageHash = {}
    let nums = []

    for(let i in array){
      let addend = sum - array[i]

       // if addend is in array
            nums.push([addend, array[i]])
        }
    }
    return nums
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;We can find the desired addend by subtracting the current element from sum, but how can we tell if it exists in the area without using another nested loop or our binary search function?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let hashTwoSum = (array, sum) =&amp;gt; {
    let storageHash = {}
    let nums = []

    for(let i in array){
      let addend = sum - array[i]

       // if addend is in array
            nums.push([addend, array[i]])
        }
          numsObj[array[i]] = i
    }
    return nums
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Let’s start using &lt;strong&gt;&lt;em&gt;storageHash&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;With each iteration, we’ll add a new &lt;a href="https://stackoverflow.com/questions/25955749/what-is-a-key-value-pair"&gt;key-value pair&lt;/a&gt; to &lt;strong&gt;&lt;em&gt;storageHash&lt;/em&gt;&lt;/strong&gt;: a &lt;strong&gt;&lt;em&gt;key&lt;/em&gt;&lt;/strong&gt; of &lt;strong&gt;&lt;em&gt;array[i]&lt;/em&gt;&lt;/strong&gt; (the &lt;strong&gt;&lt;em&gt;element)&lt;/em&gt;&lt;/strong&gt;, and a &lt;strong&gt;&lt;em&gt;value&lt;/em&gt;&lt;/strong&gt; of &lt;strong&gt;&lt;em&gt;i&lt;/em&gt;&lt;/strong&gt; (the &lt;strong&gt;&lt;em&gt;index)&lt;/em&gt;&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let hashTwoSum = (array, sum) =&amp;gt; {
    let storageHash = {}
    let nums = []

    for(let i in array){
      let addend = sum - array[i]

        if (addend in storageHash){
            nums.push([addend, array[i]])
        }
        storageHash[array[i]] = i
    }
    return nums
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now, when we find a new addend, and want to check and see if it exists in our array, we can look up that key in &lt;strong&gt;&lt;em&gt;storageHash&lt;/em&gt;&lt;/strong&gt;. This is a nice operation to do, as it only requires checking &lt;a href="https://stackoverflow.com/questions/697918/what-does-o1-access-time-mean/697935"&gt;a single specific place in memory&lt;/a&gt;, and doesn’t require iterating through a collection of connected elements.&lt;/p&gt;

&lt;p&gt;If the key exists in &lt;strong&gt;&lt;em&gt;storageHash&lt;/em&gt;&lt;/strong&gt;, then we know that number also exists in &lt;strong&gt;&lt;em&gt;array&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Thus, we can safely combine the addend we’ve checked against &lt;strong&gt;&lt;em&gt;storageHash&lt;/em&gt;&lt;/strong&gt; with our current array element, and add them to our &lt;strong&gt;&lt;em&gt;nums&lt;/em&gt;&lt;/strong&gt; array for later return.&lt;/p&gt;

&lt;p&gt;Let’s test it out in the &lt;a href="https://developers.google.com/web/tools/chrome-devtools/console/javascript"&gt;browser console&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let array = [2, 3, 4, 3, 6, 7]

hashTwoSum(array, 6)

&amp;gt; 0: (2) [2, 4]
&amp;gt; 1: (2) [3, 3]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Great! That gives returns our desired result. 🌟&lt;/p&gt;

&lt;p&gt;Rather than iterating through every possible combination of array elements, or even finding the desired addend for each element and searching the array for it (even with something as relatively efficient as a binary search), we can now look up each potential addend directly using our hash table.&lt;/p&gt;

&lt;p&gt;This approach is also nice because it doesn’t require sorting the initial array, or stripping superfluous correct combinations from the final array.&lt;/p&gt;

&lt;p&gt;That’s it! Hopefully these solutions help you tackle the challenge of finding the two array elements that add up to a given sum.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--zmdiceoy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2Ayg19jmYKWpyaANFLEbRP5Q.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zmdiceoy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2Ayg19jmYKWpyaANFLEbRP5Q.gif" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you’d like to read more about a variety of approaches to solving this problem and their respective benefits, I really like &lt;a href="https://web.stanford.edu/class/cs9/sample_probs/TwoSum.pdf"&gt;this writeup&lt;/a&gt; (&lt;strong&gt;warning: automatic pdf download!&lt;/strong&gt;).&lt;/p&gt;

</description>
      <category>twosum</category>
      <category>algorithms</category>
      <category>javascript</category>
      <category>binarysearch</category>
    </item>
    <item>
      <title>Getting Sleep() with Promises in JS</title>
      <dc:creator>noam sauer-utley</dc:creator>
      <pubDate>Mon, 04 Nov 2019 22:40:01 +0000</pubDate>
      <link>https://dev.to/noamsauerutley/getting-sleep-with-promises-in-js-5f09</link>
      <guid>https://dev.to/noamsauerutley/getting-sleep-with-promises-in-js-5f09</guid>
      <description>&lt;p&gt;&lt;em&gt;&lt;strong&gt;Note&lt;/strong&gt;: this post was originally published on &lt;a href="https://medium.com/@noamsauerutley/finding-the-top-n-per-group-with-sql-8c9a427a9fa1" rel="noopener noreferrer"&gt;Medium&lt;/a&gt; in November, 2019&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F480%2F1%2APZMeXFJzCJr3IE7g3j-ZfA.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F480%2F1%2APZMeXFJzCJr3IE7g3j-ZfA.gif" alt="a small dog sitting under a blanket and looking at an alarm clock"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Recently, I started building a very basic single page app to illustrate &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API" rel="noopener noreferrer"&gt;Fetch API&lt;/a&gt; usage in a cute and simple way.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F250%2F1%2ApSprzPedpIVMYHW5RGejpw.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F250%2F1%2ApSprzPedpIVMYHW5RGejpw.gif" alt="a dachshund putting a tennis ball into a ball-throwing machine"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F783%2F1%2AZ2aBcVI3fjHCJ0PBb3wt2A.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F783%2F1%2AZ2aBcVI3fjHCJ0PBb3wt2A.png" alt="Header: “Welcome to Dog Fetch!”. Yellow button: “Throw the ball!”. smaller text: “You have thrown the ball for: No dogs yet!”"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F480%2F1%2AIqFn91pYg2Ss5ImNM_PtXg.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F480%2F1%2AIqFn91pYg2Ss5ImNM_PtXg.gif" alt="a large brown dog jumping to catch a ball"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When the user clicks a button styled like a tennis ball, a new dog image is fetched from the &lt;a href="https://dog.ceo/dog-api/" rel="noopener noreferrer"&gt;Dog API&lt;/a&gt;, and given a name fetched from the &lt;a href="https://namey.muffinlabs.com/" rel="noopener noreferrer"&gt;Namey API&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F350%2F1%2A1e6THth06sEuMYN0LaJaYg.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F350%2F1%2A1e6THth06sEuMYN0LaJaYg.gif" alt="a yellow labrador retriever jumping into a pile of leaves of fetch a ball"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The dog’s image is loaded onto the page, and with each fetch, a name is added onto a list of fetched dogs.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F900%2F1%2AYmPp2OrBlHSpcqX_aFysSg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F900%2F1%2AYmPp2OrBlHSpcqX_aFysSg.png" alt="Header: “Look who it is!”. Below the header, a hound dog looking at the camera."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;However, once a few dogs were fetched, the &lt;a href="https://www.w3schools.com/jsref/dom_obj_document.asp" rel="noopener noreferrer"&gt;document&lt;/a&gt; content stretched down quite far, and required a bit of scrolling to view. I decided to add a handy little link in the page footer which would scroll the viewer right up to the top, and re-fire the fetch cycle.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;


    function scrollAndThrow(){
        //smooth scroll back to top left corner of window
        window.scroll({
            top: 0, 
            left: 0, 
            behavior: 'smooth' 
           })
        // then click the button to trigger a new round of fetch   
        button.click()
    }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We can just scroll up the window, then trigger a new&lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click" rel="noopener noreferrer"&gt;click event&lt;/a&gt; on the button we’ve assigned to the variable  &lt;strong&gt;&lt;em&gt;button&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;However, the the combo of the page scrolling up and the image fetch simultaneously re-firing looks pretty messy.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F480%2F1%2A4Z41QWEMYXG7iCGPc17F-g.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F480%2F1%2A4Z41QWEMYXG7iCGPc17F-g.gif" alt="the page awkwardly reloading as it autoscrolls up"&gt;&lt;/a&gt;Yikes.&lt;/p&gt;

&lt;p&gt;I wanted a way to slow things down, so the user would only see one thing happening on the page at a time.&lt;/p&gt;

&lt;p&gt;I knew that if I could just pause for half a second between the scroll and the API Fetch, everything would look much smoother.&lt;/p&gt;

&lt;p&gt;Suddenly, I missed Ruby’s &lt;a href="https://apidock.com/ruby/Kernel/sleep" rel="noopener noreferrer"&gt;&lt;strong&gt;&lt;em&gt;sleep&lt;/em&gt;&lt;/strong&gt;&lt;/a&gt; method. It was so &lt;a href="https://en.wiktionary.org/wiki/MINASWAN" rel="noopener noreferrer"&gt;nice&lt;/a&gt; to be able to schedule events to the exact time I wanted them to run!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F300%2F1%2ACN5z1yOQSEHrtS-5FBOkAg.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F300%2F1%2ACN5z1yOQSEHrtS-5FBOkAg.gif" alt="a puppy stretching in its sleep"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I decided there had to be a way to construct my own dupe of that handy little method.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F250%2F1%2AFOggOhrunoyRldm4aUY-Ww.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F250%2F1%2AFOggOhrunoyRldm4aUY-Ww.gif" alt="a dachshund wearing a hard hat and riding on a toy truck"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you’re not familiar with JS &lt;a href="https://developers.google.com/web/fundamentals/primers/promises" rel="noopener noreferrer"&gt;Promises&lt;/a&gt;, it’s important to first understand that while Javascript is &lt;a href="https://en.wikipedia.org/wiki/Thread_(computing)" rel="noopener noreferrer"&gt;single-threaded&lt;/a&gt; (meaning it can only process one &lt;a href="https://www.w3schools.com/js/js_statements.asp" rel="noopener noreferrer"&gt;&lt;strong&gt;&lt;em&gt;statement&lt;/em&gt;&lt;/strong&gt;&lt;/a&gt; at a time), it is also &lt;a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing" rel="noopener noreferrer"&gt;&lt;strong&gt;&lt;em&gt;asynchronous&lt;/em&gt;&lt;/strong&gt;&lt;/a&gt; (meaning it can start processing a new statement before the previous statement has resolved, allowing it to multitask time-consuming processes in the background.).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F446%2F1%2ARcbHviozBBiqYZ2wVMzXfA.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F446%2F1%2ARcbHviozBBiqYZ2wVMzXfA.gif" alt="a dog digging a big hole, kicking sand back onto another dog that is sleeping"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Javascript uses Promises to track the resolution of those background processes, allowing us to set certain statements to run only when a time-consuming process has resolved and returned its completed result.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F250%2F1%2ANhGha_udiTpGSWoW5MtQqg.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F250%2F1%2ANhGha_udiTpGSWoW5MtQqg.gif" alt="a small dog sitting up on its hind legs and looking out the front door as if waiting for someone"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is great for handling fetch requests and other time consuming processes, but it also gives us a way to tell our app to wait to process certain statements until exactly when we want them to be run.&lt;/p&gt;

&lt;p&gt;I realized that I could exploit this functionality by building a Promise around Javascript’s built-in &lt;a href="https://www.w3schools.com/jsref/met_win_settimeout.asp" rel="noopener noreferrer"&gt;&lt;strong&gt;&lt;em&gt;setTimeout&lt;/em&gt;&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;&lt;em&gt;()&lt;/em&gt;&lt;/strong&gt; method.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F220%2F1%2AmbLAy1wFOk7Rv1lfuavXDA.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F220%2F1%2AmbLAy1wFOk7Rv1lfuavXDA.gif" alt="a sad looking puppy sitting in the corner with the caption “He’s in time out”"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Let’s make a promise:
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout" rel="noopener noreferrer"&gt;&lt;strong&gt;&lt;em&gt;setTimeout()&lt;/em&gt;&lt;/strong&gt;&lt;/a&gt; takes in two parameters:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;1: A function to be executed after the timer expires.&lt;/p&gt;

&lt;p&gt;2: The time, in milliseconds (thousandths of a second), the timer should wait before the specified function or code is executed. If this argument is omitted, a value of 0 is used, meaning execute “immediately”, or more accurately, as soon as possible. Note that in either case, the actual delay may be longer than intended&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

return new Promise(resolve =&amp;gt; setTimeout(resolve, ms))



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We can create a new Promise, and tell setTimeout to pass the Promise resolve statement as setTimeout’s first parameter. setTimeout will delay for &lt;strong&gt;&lt;em&gt;ms&lt;/em&gt;&lt;/strong&gt; milliseconds, then &lt;strong&gt;&lt;em&gt;resolve&lt;/em&gt;&lt;/strong&gt; the promise. If we throw this in a function, we now have a handle little delay function ready to go!&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

 function sleep(ms) {
        // add ms millisecond timeout before promise resolution
        return new Promise(resolve =&amp;gt; setTimeout(resolve, ms))
      }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Great! Now we made our replacement for Ruby’s &lt;a href="https://apidock.com/ruby/Kernel/sleep" rel="noopener noreferrer"&gt;sleep&lt;/a&gt; method.&lt;/p&gt;

&lt;p&gt;Now let’s put it to use.&lt;/p&gt;

&lt;p&gt;I decided to take advantage of one of &lt;a href="http://es6-features.org/" rel="noopener noreferrer"&gt;ES6&lt;/a&gt;’s fresher bits of syntax for &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" rel="noopener noreferrer"&gt;Promise&lt;/a&gt; handling: &lt;a href="https://javascript.info/async-await" rel="noopener noreferrer"&gt;Async/await&lt;/a&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

  async function delayedClick(){
        // await sleep function promise
        await sleep(700)
        // once resolved, click button
        button.click()
    }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;delayedClick()&lt;/em&gt;&lt;/strong&gt; knows from the get that it’s awaiting a promise resolution. We’re using our brand new &lt;strong&gt;&lt;em&gt;sleep()&lt;/em&gt;&lt;/strong&gt; function as the awaited promise, passing in our desired number of milliseconds (in this case, &lt;strong&gt;700ms&lt;/strong&gt; , or &lt;strong&gt;7/10ths of a second&lt;/strong&gt; ). Once that promise resolves, we can enter the action we want &lt;strong&gt;&lt;em&gt;delayedClick()&lt;/em&gt;&lt;/strong&gt; to enact. In this case, we’re going to click the button that re-starts the fetch and display cycle.&lt;/p&gt;

&lt;p&gt;Now that we have our delay and desired action plugged into a method, we can plug &lt;strong&gt;&lt;em&gt;delayedClick()&lt;/em&gt;&lt;/strong&gt; into our existing &lt;strong&gt;&lt;em&gt;scrollAndThrow()&lt;/em&gt;&lt;/strong&gt; method as a replacement to &lt;strong&gt;&lt;em&gt;button.click()&lt;/em&gt;&lt;/strong&gt; to slow things down and clean up the onscreen process.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;


    function scrollAndThrow(){
        // smooth scroll back to top left corner of window
        window.scroll({
            top: 0, 
            left: 0, 
            behavior: 'smooth' 
           })
        // use sleep function promise to initiate 700 millisecond delay
        // then click button and initiate new fetch cycle
        delayedClick()
    }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The result: no more jaggedy mid-scroll fetch return and image load!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F480%2F1%2ALUPGETL9Zn5xMjZqtQnvGA.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F480%2F1%2ALUPGETL9Zn5xMjZqtQnvGA.gif" alt="the app smoothly scrolling up, then reloading"&gt;&lt;/a&gt;Much nicer!&lt;/p&gt;

&lt;p&gt;Sometimes, it’s just good to get some sleep!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F220%2F1%2AYvcchgBbhm_Iejp-8dUDig.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F220%2F1%2AYvcchgBbhm_Iejp-8dUDig.gif" alt="a cute puppy falling asleep"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Notes:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Want to fetch a dog? Check out the repo &lt;a href="https://github.com/noamsauerutley/doggie-fetch" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;For dog pics, I used the Dog API: &lt;a href="https://dog.ceo/dog-api/" rel="noopener noreferrer"&gt;https://dog.ceo/dog-api/&lt;/a&gt; .&lt;/li&gt;
&lt;li&gt;for random first names, I used the muffinlabs Namey API: &lt;a href="https://namey.muffinlabs.com/" rel="noopener noreferrer"&gt;https://namey.muffinlabs.com/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Using &lt;a href="https://nodejs.org/en/" rel="noopener noreferrer"&gt;Node.js&lt;/a&gt;? Turns out that there’s a handy little module built by &lt;a href="https://wesbos.com/" rel="noopener noreferrer"&gt;Wes Bos&lt;/a&gt; that keeps this functionality ready to go for you. Check out Waait: &lt;a href="https://www.npmjs.com/package/waait" rel="noopener noreferrer"&gt;https://www.npmjs.com/package/waait&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>asynchronous</category>
      <category>promises</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Finding the Top N per Group with SQL</title>
      <dc:creator>noam sauer-utley</dc:creator>
      <pubDate>Sat, 19 Oct 2019 20:16:54 +0000</pubDate>
      <link>https://dev.to/noamsauerutley/finding-the-top-n-per-group-with-sql-14j1</link>
      <guid>https://dev.to/noamsauerutley/finding-the-top-n-per-group-with-sql-14j1</guid>
      <description>&lt;p&gt;&lt;em&gt;&lt;strong&gt;Note&lt;/strong&gt;: this post was originally published on &lt;a href="https://medium.com/@noamsauerutley/finding-the-top-n-per-group-with-sql-8c9a427a9fa1"&gt;Medium&lt;/a&gt; in October, 2019&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Solving Top N per Group with SQL
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Getting to Know SQL
&lt;/h3&gt;

&lt;p&gt;When I first encountered SQL, everything about it felt… strange. Trying to use it felt alien in some way I couldn’t quite put my finger on.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--qeOXkBqD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/398/1%2A35NrCdCzNujZkWZ27EFELg.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--qeOXkBqD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/398/1%2A35NrCdCzNujZkWZ27EFELg.gif" alt="Dr. McCoy inspects an alien with a tricorder."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Trying to understand what was so different about this language, I spent some time reading about&lt;a href="https://codeburst.io/declarative-vs-imperative-programming-a8a7c93d9ad2"&gt;Declarative vs. Imperative Programming&lt;/a&gt;, as well as Codd’s &lt;a href="https://www.seas.upenn.edu/~zives/03f/cis550/codd.pdf"&gt;A Relational Model of Data for Large Shared Data Banks&lt;/a&gt; (Warning: PDF download link), and some basic info about &lt;a href="https://www.people.vcu.edu/~rhammack/BookOfProof/"&gt;Set Theory&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;It quickly became obvious how powerful and elegant SQL could be when it came to handling larger volumes of data. I could just tell SQL exactly what data I wanted, and it would utilize efficient sets to select it, instead of iterating through each individual object and getting swamped.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vIwqOJpV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/480/1%2AQgIwaS4RtrivURp8MEyTfQ.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vIwqOJpV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/480/1%2AQgIwaS4RtrivURp8MEyTfQ.gif" alt="Tribbles fall onto Captain Kirk from an overhead storage locker."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Still, the #1 most helpful thing I did was spend a weekend writing queries and seeing the results, tweaking things and observing the changes.&lt;/p&gt;

&lt;p&gt;I was introduced to &lt;a href="https://fivethirtyeight.com/"&gt;Five Thirty Eight&lt;/a&gt;’s collection of data[¹][²] about The Daily Show with Jon Stewart through a &lt;a href="https://flatironschool.com/"&gt;Flatiron School&lt;/a&gt; bonus lab[³], and found it a perfect playground to query around, using beginner-friendly SQLite.&lt;/p&gt;

&lt;p&gt;After parsing the CSV data into a SQLite database, I started trying to pull out simple bits of data.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--20s3EvTz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/400/1%2AUXrOujs-M6UNQciDknNb9A.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--20s3EvTz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/400/1%2AUXrOujs-M6UNQciDknNb9A.gif" alt="Spock pushes some buttons."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;First, as a test run, I wrote a simple query selecting all the shows from 1999.&lt;/p&gt;

&lt;p&gt;I printed the results to my console, and received a neat list of info about all 166 episodes from 1999. Success!&lt;/p&gt;

&lt;p&gt;I then tried a more specific query, and asked for the five guests with the most repeat appearances. A quick google search determined that the results I received were accurate. So far so good!&lt;/p&gt;

&lt;p&gt;I tried again, querying the top occupation for guests, and got back “Actor” (unsurprising).&lt;/p&gt;

&lt;p&gt;I played around with more simple queries, getting all the appearances from certain celebs, getting the number of guests with the same first name, the year with the most guest appearances overall, etc.&lt;/p&gt;

&lt;p&gt;I was getting the hang of this SQL thing!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0oUz0uRn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/480/1%2AOmFQ_6ETgt-GqX9zWpzLJg.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0oUz0uRn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/480/1%2AOmFQ_6ETgt-GqX9zWpzLJg.gif" alt="Spock holds a calm looking dog dressed up as an alien"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then I tried a more advanced query. Instead of asking for the top guest or occupation out of the whole table, I wanted to find the top occupation per year. I figured it would be a little bit more complicated, but not much.&lt;/p&gt;

&lt;p&gt;Except, when I started trying to write that query, I could only get a single result. I could get the most popular occupation of the whole database, or the year with the most different occupation, or something else that represented the database as a whole, but I couldn’t get a list of data representing information from each individual year.&lt;/p&gt;

&lt;p&gt;I had no idea how to direct SQL to get the data I wanted.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZVpXRrFj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/500/1%2A26SVGDV8tUyAcy9DrrkNGw.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZVpXRrFj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/500/1%2A26SVGDV8tUyAcy9DrrkNGw.gif" alt="Captain Kirk looks confused and a yeoman shrugs while surrounded by tribbles."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I needed SQL to get me a layered result — to organize the data by year, then order the information from each year and return specific positions from that ordered list as results.&lt;/p&gt;

&lt;p&gt;Every approach I could think of involved iterative sorting, which I knew wouldn’t be an effective use of this declarative, set-based tool.&lt;/p&gt;

&lt;p&gt;Suddenly, SQL wasn’t feeling as friendly anymore.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bMIfIWtf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/500/1%2AZ-mbtqIuJPOr35SUqqFvdA.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bMIfIWtf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/500/1%2AZ-mbtqIuJPOr35SUqqFvdA.gif" alt="The dog alien snarls angrily."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I did some googling, and found a surprising volume of &lt;a href="https://stackoverflow.com"&gt;Stack Overflow&lt;/a&gt;[⁴] posts devoted to finding ways to communicate this exact sort of layered demand to various SQL database types. I was intrigued.&lt;/p&gt;

&lt;p&gt;I did a little research, and learned that SQLite 3 added a handy &lt;a href="https://www.sqlite.org/windowfunctions.html"&gt;window function&lt;/a&gt; called &lt;a href="https://www.sqlitetutorial.net/sqlite-window-functions/sqlite-rank/"&gt;Rank&lt;/a&gt; that allows you to partition the rows of a SQL query’s result according to the criteria of your choice, then order those partitions as needed.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--MbdN5EdV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/400/1%2AhaY0aVVS0XALesgosKTzuw.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--MbdN5EdV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/400/1%2AhaY0aVVS0XALesgosKTzuw.gif" alt="A control panel with flashing lights."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This was exactly the tool I needed!&lt;/p&gt;

&lt;h3&gt;
  
  
  Using Rank to Solve Top N per Group in SQLite
&lt;/h3&gt;

&lt;p&gt;Let’s start with the innermost &lt;a href="http://www.sqltutorial.org/sql-subquery/"&gt;subquery&lt;/a&gt;, as set selection starts with the innermost subquery and refines outward.&lt;/p&gt;

&lt;p&gt;First things first, we want to select occupation and year from our table “shows”, and get a count of the episode guest’s occupations, which we’ll reference as occupation_count. The results are &lt;a href="https://www.geeksforgeeks.org/sql-group-by/"&gt;grouped by&lt;/a&gt; year, then by occupation, so that we can get that occupation count per year.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        SELECT occupation, year, COUNT(occupation) AS occupation_count
        FROM shows
        GROUP BY year, occupation
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This gives us the base data we want to organize and select from — SQL can ignore everything else.&lt;/p&gt;

&lt;p&gt;Next, our middle subquery should use Rank to partition this data by year, making each year’s data into its own set. Then, it will create a ranking within each year, ordered by occupation_count, which we’ll call occupation_count_rank.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      SELECT occupation, year, occupation_count,
      RANK () OVER (
        PARTITION BY year
        ORDER BY occupation_count DESC
      ) occupation_count_rank
      FROM (
        SELECT occupation, year, COUNT(occupation) AS occupation_count
        FROM shows
        GROUP BY year, occupation
      )
      GROUP BY year, occupation

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now, we’ve got out occupations ranked in descending order by frequency, per year. This is also grouped by year first, then by occupation, as we want our query result to be ordered within those groups.&lt;/p&gt;

&lt;p&gt;We’re already quite close to our desired query result, thanks to Rank, so our outer query can be quite simple. It simply selects the occupations from the result set supplied by the previous subquery, and returns only the occupations where the occupation_count_rank is equal to one. As we ordered our rank in descending order, the occupation with the highest count will be first.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    SELECT occupation
    FROM (
      SELECT occupation, year, occupation_count,
      RANK () OVER (
        PARTITION BY year
        ORDER BY occupation_count DESC
      ) occupation_count_rank
      FROM (
        SELECT occupation, year, COUNT(occupation) AS occupation_count
        FROM shows
        GROUP BY year, occupation
      )
      GROUP BY year, occupation
    )
    WHERE occupation_count_rank = 1;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;If we throw this query into a &lt;a href="https://www.rubyguides.com/2018/11/ruby-heredoc/"&gt;heredoc&lt;/a&gt; and plug it into a ruby method, we can easily view the query result in the console.&lt;/p&gt;

&lt;p&gt;Our query result? It’s just “actor”, seventeen times in a row. One for each year in our table. Which, again, unsurprising.&lt;/p&gt;

&lt;p&gt;Okay, not super exciting. Still, that means that all three layers of our query are doing their jobs, and organizing the data to get exactly the results we want!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EOsHLt5G--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/498/1%2A_J_A--__0CK0cvolhCsvVw.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EOsHLt5G--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/498/1%2A_J_A--__0CK0cvolhCsvVw.gif" alt="Captain Kirk is joined by Dr. McCoy and Spock on the bridge."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What if we didn’t want to just see actor listed out 17 times though?&lt;/p&gt;

&lt;p&gt;Let’s shake things up a little.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    SELECT year, occupation
    FROM (
      SELECT occupation, year, occupation_count,
      RANK () OVER (
        PARTITION BY year
        ORDER BY occupation_count DESC
      ) occupation_count_rank
      FROM (
        SELECT occupation, year, COUNT(occupation) AS occupation_count
        FROM shows
        GROUP BY year, occupation
      )
      GROUP BY year, occupation
    )
    WHERE occupation_count_rank &amp;lt;= 5;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Here, we’ve kept both of our subqueries the same, only changing our outermost query. Instead of selecting just the occupation, let’s select the occupation AND the year, so we can keep things nice and organized. Then, instead of selecting only the occupation with occupation_count_rank equal to 1, we’re selecting the top five occupations for each year[⁵].&lt;/p&gt;

&lt;p&gt;This gives us a lot more information! SQL returns the 5 most popular occupations for daily show guests, and also notes the year for us, so we don’t lose track halfway down the list.&lt;/p&gt;

&lt;p&gt;Let’s make sure this is actually flexible — we can return the top one or top five per group, but let’s change what we’re returning.&lt;/p&gt;

&lt;p&gt;Let’s write another similar query, this time querying the “genre” column of our database, which describes the genre of the guest’s Daily Show appearance. Let’s keep it clean this time, and only return the genre (not the year), and ask for the top 3 genres per year.&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;```    SELECT genre&lt;br&gt;
    FROM (&lt;br&gt;
      SELECT genre, year, genre_count,&lt;br&gt;
      RANK () OVER (&lt;br&gt;
        PARTITION BY year&lt;br&gt;
        ORDER BY genre_count DESC&lt;br&gt;
      ) genre_count_rank&lt;br&gt;
      FROM (&lt;br&gt;
        SELECT genre, year, COUNT(genre) AS genre_count&lt;br&gt;
        FROM shows&lt;br&gt;
        GROUP BY year, genre&lt;br&gt;
      )&lt;br&gt;
      GROUP BY year, genre&lt;br&gt;
    )&lt;br&gt;
    WHERE genre_count_rank &amp;lt;= 3;&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

This tells us that “Acting” is usually in first place, but as the years go by, the more general “Media” begins to take over. “Comedy” and “Music” usually fill the remaining spot for the first years, but later in the 00’s, “Politician” becomes increasingly common, revealing a shift in the show’s tone.

Thanks, SQL.

![Lt. Uhura happily holds a purring tribble up to her ear.](https://cdn-images-1.medium.com/max/245/1*rAostJnbsZvaDH_Ac9wvwA.gif)

I queried a SQLite database in the above examples, but most popular SQL software include the RANK() function. If your preferred SQL software doesn’t have a rank function, I’d recommend looking into using a temporary table as a workaround, as explained [here](http://allenbrowne.com/ranking.html#temptable).

Notes &amp;amp; Links:

[1]: [Every Guest Jon Stewart Ever Had On 'The Daily Show'](https://fivethirtyeight.com/features/every-guest-jon-stewart-ever-had-on-the-daily-show/)



[3]: If you are a Flatiron Student and would like to talk about this lab, feel free to contact me via [Twitter](https://twitter.com/thevoidbutcozy).

[4]: Support labor unions in tech!

[5]: In the case of a tie, Rank will return both tied elements, and skip the value that would have held the second element were it not tied. If this will cause issues for you, look into using [Dense Rank() ](https://www.sqlitetutorial.net/sqlite-window-functions/sqlite-dense_rank/)instead!
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

</description>
      <category>sql</category>
      <category>sqlite</category>
      <category>programming</category>
      <category>flatironschool</category>
    </item>
  </channel>
</rss>
