Understanding Big O notation - Cracking the Coding Interview

前端 未结 3 1202
悲哀的现实
悲哀的现实 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.

    0 讨论(0)
  • 2021-02-05 10:53

    In general the printing of a constant length string is considered constant as well, but if we want to be precise let's consider the print of a single character as the basic operation: this means that to print a k length string we have O(k).

    Since we have O(ck) possible strings and for each of them we have to check if it is sorted (with O(k)) and to print them (another O(k)), the total complexity became O(ck(k + k)) = O(2ckk).

    But multiplying a function for a constant factor doesn't change it's complexity, and therefore the answer remains O(ckk).

    0 讨论(0)
  • 2021-02-05 11:11

    Printing the string is only an extra addition to the k time.

    Checking whether each string is sorted is O(k) and say that printing it is O(dk) for some integer d (a constant). Adding the two we get O(k + dk), which can be re written as O(k(1 + d)). Because this just a scalar we know O(k + dk) = O(k) so the answer does not change.

    0 讨论(0)
提交回复
热议问题