All Possible Codes

One of the most famous interview questions is to generate all possible codes given a string. Here is the extract from http://www.careercup.com/page?pid=facebook-interview-questions&sort=comments:

If a=1, b=2, c=3,....z=26. Given a string, find all possible codes that string can generate. Give a count as well as print the strings.
For example:
Input: "1123". You need to general all valid alphabet codes from this string.

Output List
aabc //a = 1, a = 1, b = 2, c = 3
kbc // since k is 11, b = 2, c= 3
alc // a = 1, l = 12, c = 3
aaw // a= 1, a =1, w= 23
kw // k = 11, w = 23


Notice that the induction part of the recursive solution isn't that complicated because we're only dealing with a mapping of either one digit (1-9) or two digits (10-26). The base case is simple. It seems exponential or highly polynomial, but works fine with moderate input size.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AllPossibleCodes
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: AllPossibleCodes.exe <number>");
                return;
            }

            Process(args[0], "");
        }

        static void Process(string number,
                            string code)
        {
            if (number == null ||
                number.Length == 0)
            {
                if (code != null &&
                    code.Length > 0)
                {
                    Console.WriteLine(code);
                }
                return;
            }

            Process(number.Substring(1), code + (Convert.ToChar('a' + (number[0] - '0') - 1)).ToString());
            if (number.Length > 1)
            {
                int n = Convert.ToInt32(number.Substring(0, 2));
                if (n <= 26)
                {
                    Process(number.Substring(2), code + (Convert.ToChar('a' + n - 1)).ToString());
                }
            }
        }
    }
}

Comments

Popular posts from this blog

Changing the root of a binary tree

Prompt Engineering and LeetCode

ProjectEuler Problem 719 (some hints, but no spoilers)