Subtle nuances of Big O notation for computation complexity

二次信任 提交于 2021-02-11 07:08:55

问题


I was just working on a LeetCode problem, Roman to Integer, the conversion of Roman numerals to integers, and after finishing up and comparing solutions, I noticed a rather interesting nuance in how the solutions listed describe their computational complexity.

I had described my solution as O(n), linear with the number of input elements, as my solution iterated over the elements of a Roman numeral character by character. The official solutions, however, described how with numerals I, V, X, L, C, D, and M, only numbers from 1 to 3999 can be expressed. Their argument was that because Big O only considers the worst case, and the worst case is fixed at 3999, time complexity is constant at O(1), regardless of process.

This begs a really subtle question. When we say "worst case performance," are we referring to worst case within any given size of n, or across all n. Do we consider, for a given n, the worst case performance, or do we consider the specific choice of n that gives us the global worst case performance?


回答1:


A great question!

Well, it's more like 'across all n' is the answer to your question.

Lets dive into it: because, with roman numerals, we can only express elements up to 3999. So, we can create a program, that over a certain number, will just return "Failure". thus, we don't need to even read the whole string to answer our question! we can see, that in the Roman to Integer problem, our running time is bounded above by some consonant, so we can say it's O(1).

Do you have some experience with infinitesimal calculus? because this is actually just that! the time complexity, is the bound when your input size approach infinity. we discard every finite number of "the first n cases", and we are only interested in the answer for "big" n.



来源:https://stackoverflow.com/questions/61960113/subtle-nuances-of-big-o-notation-for-computation-complexity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!