October 23, 2013

Interview Question - Get Permutations of a String

My algorithm follows the same idea as Gayle's in Cracking the Coding Interview, I've just implemented it iteratively instead of recursively

public static List<string> GetPermutations(string input)
{
   var permutes = new List<string>();
   for (int i = 0; i < input.Length; i++)
   {
      if (i == 0)
      {
         permutes.Add(input[i].ToString());
      }
      else
      {
          var newPermutes = new List<string>();
          foreach (string word in permutes)
          {
             AddCharToEveryPosition(input[i], word, newPermutes);
          }
          permutes = newPermutes;
      }
  }
  return permutes;
}

private static void AddCharToEveryPosition(char c, string word, List<string> newPermutes)
{
   for (int i = 0; i <= word.Length; i++)
   {
      string newWord = word.Insert(i, c.ToString());
      newPermutes.Add(newWord);
   }
}

I'll run through the algorithm a bit since it helps me to understand what's going on.

Say input is "meh"
We take the first letter 'm'
Then we take the second letter 'e' and add it wherever we can to the first letter.  For now we can't go too crazy, we just get { "em", "me" }
Third letter is slightly more interesting, since we now get { "hem", "ehm", "emh", "hme", "mhe", "meh" }
You can imagine how crazy it gets with more letters.

Yay permutations!