Understanding Big O notation - Cracking the Coding Interview

前端 未结 3 1245
悲哀的现实
悲哀的现实 2021-02-05 10:17

I need help understanding how the author got the answer of problem 11 in the Big O chapter.

The problem goes like this:

The following code prints

3条回答
  •  甜味超标
    2021-02-05 10:53

    In short, no. The correct answer is O(kck) as in the book.

    After you went over a string to check if its characters were ordered, which would take O(k), printing it would add only O(k) - which does not change your complexity.

    Suppose testing whether a string is ordered takes a*k operations, and printing it takes b*k. Then the total number of operations for each string is at most (a+b)*k which is still O(k).

    Edit: Regarding the second part of your question, going over all words with some fixed length will result in an exponential runtime complexity, since there are ck such words where c is the size of the alphabet and k is the length of the word.

提交回复
热议问题