3

I have this code,

void Generate(List<string> comb, string prefix, string remaining)
{
       int currentDigit = Int32.Parse(remaining.Substring(0, 1));

            if (remaining.Length == 1)
            {
                for (int i = 0; i < dictionary[currentDigit].Length; i++)
                {
                    comb.Add(prefix + dictionary[currentDigit][i]);
                }
            }
            else
            {
                for (int i = 0; i < dictionary[currentDigit].Length; i++)
                {
                    Generate(comb, prefix + dictionary[currentDigit][i], remaining.Substring(1));
                }
            }
}

What is the time complexity of the above code?

Is it Generate is O(n) and that itself is being executed n times so O(n^2)?

dictionary is len = 10 and has phone keypads stored it in. 2 = "abc" etc.

The initial call to this code will be like

Generate(new List(), "", "12345");

Thanks.

3
  • It seems to depend on dictionary[currentDigit], not posted. Commented Nov 27, 2011 at 19:14
  • what is n? is remaining initial size? I guess your dictionary size is 10 at most. Commented Nov 27, 2011 at 19:17
  • Posted the dictionary[size]. FYI - this code is from a answer in SO, so was interested in understanding the time complexity of it. Commented Nov 27, 2011 at 19:29

1 Answer 1

1

Assume dictionary size is m and input string size is n (remaining) this will be:

T(1) = m + constant;
T(n) = m T(n-1) + O(n) ==> T(n) = O(m^n)

In fact in each running of else part, you will run m times, function of O(n).

Sign up to request clarification or add additional context in comments.

5 Comments

Sorry I've overlooked that this is recursive method
@saeeda-amiri - I didn't get your last sentence, how did it change to O(mn^n)? Shouldnt it still stay as O(m^n)
@parsh yes you are right, I'll edit it as first, but If you want to comment for someone, in his answer or post there is no need to use @. Also if this answers your question mark it as answer.
Sorry posting for the first time, will try to catch up to the rules.
@parsh no matter dude, and these aren't rule, just hint to do your job faster and cleaner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.