<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Amy Berg on Medium]]></title>
        <description><![CDATA[Stories by Amy Berg on Medium]]></description>
        <link>https://medium.com/@aberg2014?source=rss-38ec14f3a691------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*X48ktena44EVZxoQ.</url>
            <title>Stories by Amy Berg on Medium</title>
            <link>https://medium.com/@aberg2014?source=rss-38ec14f3a691------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:25:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aberg2014/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Recursively Generating String Permutations]]></title>
            <link>https://medium.com/@aberg2014/recursively-generating-string-permutations-381b4ad9588?source=rss-38ec14f3a691------2</link>
            <guid isPermaLink="false">https://medium.com/p/381b4ad9588</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Amy Berg]]></dc:creator>
            <pubDate>Sun, 29 Jul 2018 20:29:04 GMT</pubDate>
            <atom:updated>2018-07-29T20:39:17.244Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*tJzX9fBWl6ALiN94cbzIHw.jpeg" /><figcaption><a href="https://cdn-images-1.medium.com/max/1600/1*appBwh6_RtvocVxwqpplHA.jpeg">Here we go again</a></figcaption></figure><p>No, young developer, don’t run away! Trust me, the recursive solution for finding permutations of a string is actually not scary! In fact, let’s take a look at this problem first without even mentioning recursion.</p><h4>If I told you right now to come up with all permutations of the string “TWO”, how would you do it?</h4><p>Remember that a permutation is just a scrambling of the letters of the word. When we are finding permutations for ‘TWO’, we are basically just deciding which letters to fill in three spaces ( _ _ _ ). Now that that’s out of the way, this is how I would find all the permutations:</p><ol><li>Start with the letter <em>T</em> and find the permutations that must start with <em>T</em>. Clearly the only permutations that start with <em>T</em> are ‘<strong>TWO</strong>’ and ‘<strong>TOW</strong>’. Add them to our list of permutations.</li><li>Next take the letter <em>W</em> and find the permutations that start with it. This yields ‘<strong>WTO</strong>’ and ‘<strong>WOT</strong>’. I could do this in my sleep!</li><li>Finally look at <em>O</em>. The permutations that start with <em>O</em> are ‘<strong>OTW</strong>’ and ‘<strong>OWT</strong>’. What a breeze!</li></ol><p>Oh wow, what do you know, we found all of the permutations for our string. And just like I promised, I didn’t mention the <em>word-that-shall-not-be-named</em> even once.</p><h4>But what if I told you that this approach is actually recursive?</h4><p>Yes, that’s right. If you are finding your string permutations this way, you are actually employing a recursive methodology. Why don’t I rewrite what is happening…</p><ol><li>We take our first letter <em>T</em>. What do we put after it? Why, nothing but the possible permutations of our remaining letters <em>W</em> and <em>O</em>. The permutations of those two letters are easy: ‘<strong>WO’</strong> and ‘<strong>OW</strong>.’ Thus we end up with ‘<strong>TWO’</strong> and ‘<strong>TOW</strong>.’</li><li>Then we take our second letter <em>W</em>. What do we put after <em>W</em>? Well, our remaining letters are <em>T</em> and <em>O</em>, so we find all the permutations of those two letters. Those permutations end up being <strong>‘TO’</strong> and <strong>‘OT</strong>.’ All the permutations that start with <em>W</em> are therefore ‘<strong>WTO’</strong> and ‘<strong>WOT</strong>.’</li><li>Hopefully you have detected the recursive pattern now. The remaining permutations of ‘TWO’ must start with <em>O</em>. We find the permutations of the remaining letters <em>T</em> and <em>W</em>, which are ‘<strong>TW</strong>’ and ‘<strong>WT</strong>’, and we place them after <em>O</em>. This gives us the permutations ‘OTW’ and ‘OWT.’</li></ol><h4>So we actually DO understand conceptually how to use recursion to find all permutations of a string..</h4><p>Let’s dive into some code. Here a JavaScript function that applies the exact same recursive approach we used in our example.Take a moment to look over it and see if you can recognize how it lines up with the process we employed above.</p><pre>function findPerms(str) {<br>  if (str.length === 1) return [str]<br>  <br>  let all = []</pre><pre>  for (let i = 0; i &lt; str.length; i++) {<br>    const currentLetter = str[i]<br>    const remainingLetters = str.slice(0,i) + str.slice(i+1)</pre><pre>    const permsOfRemainingLetters = findPerms(remainingLetters)<br>    <br>    permsOfRemainingLetters.forEach(subPerm =&gt; {<br>      all.push(currentLetter + subPerm)    <br>    })  <br>  }</pre><pre>  return all</pre><pre>}</pre><p>This recursive function has a base case when the string has length 1. A string of length 1 has only one permutation, so we return an array with that sole permutation in it. (We are assuming for the sake of this example that we only pass nonempty strings to this function. An empty string does technically have one permutation — the empty string.)</p><p>We jump into the recursive case whenever the string is longer than one character. In the recursive case we iterate over the string in a for-loop, at each iteration examining one letter from the string to call our currentLetter. This is exactly what we did in our example; we started with <em>T</em> as our currentLetter, in our next iteration <em>W</em> was the currentLetter, and in the final pass through, <em>O</em> was the currentLetter.</p><p>The next step in our code uses the slice method to find all of the remainingLetters in the string. Thus when the currentLetter is <em>T</em>, remainingLetters is the string ‘<em>WO</em>.’</p><p>Now we finally get to our actually-not-at-all-scary recursive call! We look at the remainingLetters ‘<em>WO</em>’ and find all of the permutations of them by passing remainingLetters back into our findPerms function. This returns an array of permutations: [‘<strong>WO</strong>’, ‘<strong>OW</strong>’]. (If you are unsure about how this recursive call plays out with respect to the call stack, I highly recommend you run <a href="https://repl.it/@AmyBerg/DarkAcclaimedAccess">this code</a> in which I have strategically placed some console.logs.) For each of those sub-permutations, we take our currentLetter <em>T</em> and add it to the front, then add that full permutation to our <em>all</em> array. The recursive case continues to loop over each letter until we are at the end of our string and we have added all of the permutations to the <em>all</em> array.</p><p>Ta-da! Now go forth and generate permutations to your heart’s content! But be warned, this O(n!) function might no longer be intimidating to you, but it will definitely crash your browsers with long-enough strings!</p><p>(Oh, and if you want to see a different approach to generating all permutations of a string, check out <a href="https://www.youtube.com/watch?v=ufi88cvL0Pk&amp;feature=youtu.be">this video</a> of mine that presents a non-recursive solution)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=381b4ad9588" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>