169 points · by abrahms · 13y ago · 78 comments
What O(N) means is there is some large enough number where the run-time (edit: or any function really) is bounded by a constant times the input size for any input size larger than that number (see, math, not hard). That constant may be so large that an O(N^2) may be a better solution for any practical purpose.
EDIT: As an example of this we can look at two multiplication algorithms, Karatsuba and Schönhage–Strassen, the latter having better asymptotic performance but that really kicks in once you have large enough numbers (100,000 digits or so). ( http://en.wikipedia.org/wiki/Sch%C3%B6nhage%E2%80%93Strassen... )
n^2 is less than n^3 right?
But is 2 * n^2 + 100 less than n^3?
Depends on how big n is, right?
Big O notation just assumes that n is big enough to make the answer "yes."
A good implementation could check problem sizes beforehand and chose the algorithm accordingly.
What I don't agree with is that "big O only matters for big input sizes". Big is not really a well-defined term. The problem here is that "big" depends entirely on the algorithms. It might also be n > 10. There's nothing in the definition of the landau symbols that prevents that.
You kind of need to know what a function is. That's not hard to explain either. Let's say we have f(x) = y. If I already lost you here let me know.
We say f is of O(N) (and this is a notation, not a function) if there exists two numbers, n1 and c such that for every n>n1 f(x)<cx. An example:
f(x) = 5
xI can pick c = 6, n1 = 1, it's clear that for every value > 1 6x > 5 x. I just proved this function is O(N).
Note that f(x) = 1,000,000 + 5*x is also O(N), I just need to pick a large enough c and n1.
f(x) = x^2
There no c and n1 that will make the statement above true. f is not O(N).
F1(n) = 1 second * n + 1 day = O(n)
F2(n) = 1 millisecond * n + 1 month = O(n)
F3(n) = 1 nanosecond * n ^ 2 + 1 millisecond = O(n^2)
For really big numbers both F1 and F2 are faster but at n = 100 F3 has a huge lead and for say n = 1 billion F3 beats F1 but not F2.Another example of this is that a good system/library sorting function will sometimes use an asymptotically fast algorithm like quicksort or mergesort only for arrays over a certain size, but will switch over to a O(n^2) algorithm like insertion sort to sort smaller arrays, because it has smaller constants and coefficients. (But sometimes this is overkill, because if n is small, you probably aren't going to notice the speed difference anyway.)
So yes, Big O is all about asymptotic behavior, which basically means, the rate of growth as n approaches infinity. Because a large value of n is when the choice of algorithm starts to really matter for performance.
To be clear, I really appreciate the writeup. I just wish it had been framed better. It should be clear that this is for beginner programmers, regardless of whether they have a degree or whether they're self-taught.
Not trying to berate the OP. I'm trying to say I wish OP had framed it better.
but the idea that Big O is "scary" is just absurd.
To you. I never studied things like these in school and getting to a point of "Oh that's what that means" was long and arduous as it pertained to a lot of scientific literature.Plain English, it seems, isn't in the tool set for a lot of very smart people who, coincidentally, feel that it's their duty to Explain All the Things. It's unfortunate that so many of them are deluded by the "x should be elementary" mindset or the like without regard to the language they use or the specificities of notation (Big-O in this case).
I wish computer scientists can be more like Neil deGrasse Tyson. http://www.youtube.com/watch?v=1ulkX-DA9BM
The correct way to "understand these things" is to learn the math, the theory, and do the exercises.
Would you take a scientist seriously if they didn't understand what the scientific method was?
You're right. English is not the tool to use here in explaining theory, it's not capable of it. Mathematics and programming languages are!
I was pointing out that the "x is elementary" attitude doesn't help the process and I thought (from the video at least) some empathy in communication is warranted. It's ridiculous to expect clarity when no such thing exists in the language used to describe an idea in the first place. The OP went to the trouble of making such a post. Maybe it wasn't perfect, but it gets the ball rolling.
Whatever inadequacies can be corrected with feedback and I for one would like to see more people engage in humane explanations for things pertaining to their expertise.
Big-O is "technical". Understanding of it comes with clear explanations.
No where did I claim anything contrary to : "The correct way to "understand these things" is to learn the math, the theory, and do the exercises." What I claimed was that language can soften the barrier to learning these as I imagine it did for you.
I would actually advise you to not brag about being "self-taught in psychology" because it's a very strong indicator that you don't know what you're talking about.
I think computer science has a bad wrap for being useless brain-teasers used only in interviews (within a subset of the target demographic of this article). Through the bits I've managed to pick up, I feel like they contribute to a better understanding of programming on a broader spectrum.
While you may not see a body of knowledge that many people expect you to know (that you don't know) as scary, I can assure you that many people do. There are many similar topics that induce some amount of fear in me still: issues around multi-threading and race conditions, cryptography, deep understanding of networking stacks, and compilers to name a few.
I'd also like to point out some of the phrasing you've chosen. 'the idea that Big O is "scary" is just absurd' -> 'If you can't reason about algorithms, you may not be a very good programmer'. This is the source of fear among self-taught programmers (and the source of my own fear in the above examples). We all want to be good at what we do, so let's try to lift each other up! :)
The work you're doing is wonderful. The problem I had with it is that a simple modification to it (not phrasing it in a condescending way toward self-taught programmers) would've made it so much better.
Where I've worked and hired people -- in San Francisco and Silicon Valley -- there is little emphasis placed on formal eduction. Virtually none. Some companies have a reputation for liking degrees. Google, for example, but they are an exception.
I don't think a self taught programmer, who takes his craft seriously and learns not just practical how-to but also data structures and algorithms, is at ANY disadvantage in today's job market.
Speaking of worst-case (or best-case, average-case, etc.) scenarios, how does big O notation relate? The variables inside an O() notation as far as I know refer only to the size of the input, so when we say that finding a value in an unsorted list is in O(n), we're referring to the worst-case scenario (obviously, finding a value in a list when that value is the head of the list is constant time, and not very interesting). Of course, that's a simplistic example, but with more complex algorithms like Quicksort, when we say it's in O(n log n) we're talking about average-case. Is this just because we know that worst-case performance in Quicksort is exceedingly rare so we don't bother mentioning that O(n log n) is average-case unless we're studying it more deeply?
In the case of Quicksort, I think the answer to your question is yeah, pretty much. I mean, cases where you're dealing with nearly-sorted input are common in some domains and in that case you should be very much aware of the worst-case behavior of Quicksort, but otherwise I think the discussion from CLRS puts things in perspective: even if you had the bad luck of only ever receiving input sequences such that every partitioning led to a 99-to-1 split, then your running time is still going to be O(n lg n), since your recursion tree is going to be at most log-base-100/99(n) levels tall, which is the same as lg n / (lg 100/99), the denominator there being a constant factor that disappears in an asymptotic context.
There are two things going on.
First, when we talk about Big-O we're not talking about the "worst case scenario." Big-O gives us an upper bound on the worst case scenario, but the actual worst case scenario might be better. Big-O means "no worse than" not "as bad as."
When most people say Big-O they really mean Big-Θ, which does encapsulate the idea of "asymptotically equivalent, up to a constant." See my answer on Quora for more technical details.
Second, Big-O and other forms of notation used in the asymptotic analysis of functions were invented before physical computers existed. They're statements about pure functions.
When applied to the analysis of algorithms the function we're "really" analyzing isn't the algorithm. Rather, if we have an algorithm A that takes as its input a positive integer n, we're really analyzing the function "the length of time it takes algorithm A to run given input n."
The up-to-a-constant nature of Big-O notation is nice because that constant can encapsulate things like processor speed, memory access times, and so forth. This enables us to make intelligent statements about algorithms per se without reference to the underlying machine on which the algorithm might be implemented.
Even with ideal functions, this naïve asymptotic analysis has some problems. For a toy example, imagine a spiky function like this:
f(n) = 800*n^2 if n is divisible by 1000000000
f(n) = 400*n otherwise
This function is not O(n) but it is O(n^2). The "worst case" behaves like O(n^2), but for "most inputs" it behaves like O(n). We can't say "f(n) is asymptotically no worse than n, up to a constant" because for infinitely many inputs it is.Lots of algorithms behave like this in practice because we optimize for common cases perhaps at the expense of less common cases. "Common" is dictated by how our algorithm is used.
Taking quicksort as an example, let's call the algorithm Q. We want to measure its running time given an input of length n. For input x, let's say it's running time is T(x).
Well, there are many x such that len(x) == n, so what does it even mean to say "its running time given an input of length n?" Are we given a particular input of length n? A uniformly-selected-but-random input of length n? To the extent that we can, we want to be making statements about the algorithm per se, not statements about the algorithm given a particular input.
On way to answer this to ask "Given an input of length n, what's the most time my algorithm could take?" In that case we're analyzing the following function:
W(n) = max { T(x) | x is valid input and len(x) == n }
On the other hand, maybe we care more about the average case. Perhaps we randomly pick 1,000 inputs of length n and average the running time. Now we're talking about something that looks more like a probability distribution than a discrete thing like "running time" because we've sampled the input space.And in fact, we could calculate "expected running time given input n" in this way and graph that. We could then make Big-O like statements about that new function, which is the kind of thing folks mean when they talk about "average case."
Hope that helps!
> Big-O is concerned with worst case performance. Colloquially, f∈O(g) means that "Eventually, f performs no worse than g."
Aren't these two different concepts? Worst case performance deals with the worst possible input of any given input size (like pathological inputs to Quicksort), while asymptotic performance is talking about sufficiently large inputs (like the vertical lines you've drawn on the graphs).
When I say that merge sorting a set of n elements is in O(n lg n), I'm saying that there's some value on the n axis beyond which n lg n >= MergeSort(n). But when I say that Quicksort is O(n^2) in the worst case, it's as if I'm talking about another other function called WorstQuicksort which when given a set of n items always takes as long as Quicksort would take to sort the most pathological set of n items, and there is some value on the n axis beyond which n^2 >= WorstQuicksort(n).
Link: http://web.mit.edu/16.070/www/lecture/big_o.pdf
My understanding --
A bounding function is when we know the exact function and its end-points from an algorithm. We know the extremes. i.e C1 and C2. i.e a Function falls within that boundary, it will always stay within that box(end-points). C1 and C2 are 2 lines, making a rectangle.
- Worst case, Best case, average case are different input cases, under which the algorithm grows in different ways. And we use BigO notation to classify them under easier functions, based on the order of Growth of a function.
And unless we don't know that exact function, its not possible to predict for any input variables. So don't call Big O as any bounding function, unless we know c1 and c2 <end bounds>.
- Big O is a notation that characterizes functions according to their growth rates.
- Different functions with the same growth rate may be represented using the same O notation.
- The letter O is used because the growth rate of a function is also referred to as order of the function. A description of a function in terms of big O notation usually only provides an upper bound on the growth rate of the function.
To be fair, it is pretty common to be a little bit sloppy with this definition. People often say O(...) when they really mean Θ(...).
It's a different meaning of "order", that has to do with the shape of the size-vs-time curve. It's the same meaning as the order of a polynomial ("x" is linear or 1st order, "x^2" is quadratic or 2nd order, etc).
but Big-O is all about the approximate worst-case performance of doing something.
It can be, but I think it's more commonly taken to mean the average case. One example is quicksort, which is O(n*log(n)) on average but can be quadratic (n^2) in the worst case.
Let ℜ be the set of all real numbers. Let F(ℜ) be the set of all functions f: ℜ → ℜ. Let X be a set and 𝒫(X) be the power set of X, i.e., the set of all subsets of X.
Then "O" is a function O: F(ℜ) → 𝒫(F(ℜ)) such that
O(g) = { f ∈ F(ℜ) : limsup_{x→∞} f(x)/g(x) < ∞ }
That is, O takes as its input a function from the reals to the reals and returns a set of all functions which are in its "Big-O" class.That seems really, really pedantic and not particularly illuminating.
This stuff isn't scary. It's thick but learnable and you can even develop an appreciation for its elegance.
You have two functions, x^4 and x^3. You can multiply x^3 by any constant multiple a (any number, regardless of size), and as x gets sufficiently large x^4 will be bigger than a * x^3. This is the point of evaluating asymptotic performance: as your input data approaches an infinite size, only the highest order term in a polynomial really matters. For example, x^2 + x + 1 will approach x^2 for sufficiently large x - the lower order terms (x^1 and x^0) don't really matter for a big x.
Technically, big-O refers to a bounding function: x^2 is O(x^2) AND O(x^3), etc. because x^2 is less than or equal to x^2 and x^3 as you approach infinity. For convenience we're usually only interested in the best fit; it's useless to say your algorithm is faster than O(x^5), but it's interesting if it's O(n).
Finally, we also have small-oh notation, which is a lower bound. If your algorithm is never faster, on an ideal input set, than x^2, it's also o(x^2). Note that the same algorithm is also o(n) and o(1), because any algorithm which is slower than (or equal to) x^2 must necessarily be slower than x or 1 (constant-time).
edit: It's worth pointing out I only talked about polynomials because it's pretty intuitive. You can extend this notation to any class of functions - exponentials, logarithms, etc. but you just have to know that log(x) is O(x) and o(1), etc.
Little-oh is a strict upper-bound. If `f` is `o(g)` then
lim_(x -> inf) f(x)/g(x) -> 0.
Or something. It has been a while. If you want an asymptotic lower-bound you want big Omega (non-strict) or little omega (strict).SELECT a, b, c FROM abc (30,000 rows)
BEGIN
SELECT e, d, f FROM edf WHERE e = a (30k * 1m)
BEGIN
SELECT x, y, z FROM xyz WHERE d = x (30k*1m*500k scanned)
BEGIN
process()
END
END
ENDA customer or manager can all find respect in lowering the growth rate of a query. No mathematics required. Simply, "Your report now runs in 30 seconds instead of 20 minutes." Anyone can compute that!
The mathematics of Big-O gets annoying for average case scenarios. Instances of
def fun(abc):
l=[]
for x in abc:
if x%2==0:
for y in abc:
l.append(y)
return lYou can actually see about 100 gumballs in the picture, so there must be far more hidden behind them -- my guess is closer to 500, which is about twice as close (in order-of-magnitude) to 1000 as to 100.
For all we care , we can write the Big O of
for ( i = 0 ; i < n ; i++) { cout<<"I am constant time operation"; }
as O( n!) , it won't be mathematically wrong but again it would be very misleading and loose :). So my advice to everyone is to use the Big Θ notation
As f(x)= Big Θ(g(x)) when f(x) = Big O ( g(x) ) and Big Ω(g(x)) .
Here for those that don't know what Big Ω(g(x)) (read Big omega) is, it is a lower bound . In English that would be that your loop will execute/iterate at least g(x) times.
Now before people get any more confused Big Θ(g(x)) is a tight bound , that means that your code/loop will run at least C1 * (g(x)) and at most C2 * (g(x)) . where C1 and C2 are two constants .
If anyone is interested they should really read CLRS. It has an excellent chapter on calculating and explaining the time complexities.
so my point is if f(N) = O(N) then f(N) is also equal to O(N^2) as f(N) <= C
N^2 .One thing I would stay away from is the talk about "orders of magnitude" because the order of a function and an order of magnitude are very different topics, and it could cause a reader to make bad conclusions like "one algorithm takes 10 seconds to run, one take 100 to run, they must have different big-O notation". I understand why the analogy is made, it's because you're estimating things from a high level, but I think it could cause confusion on the fundamentals.
That said, I got ~500 gumballs in the machine ((container diameter / gumball diameter)^3 * .64) so both guesses of 100 and 1000 should be within an order of magnitude. ;)
So rounding 500 to the nearest order of magnitude gives 1000. 310 is the mid point.
As everyone knows, calculus is based on limits, but when handled rigorously limits have a lot of subtle pitfalls that take a lot of work to deal with. For example, given a function f(x,y), if we want to take one limit after another, the result might depend on the order in which the limits are taken. In other words, taking limits is not commutative unless certain conditions are satisfied.
None other than the great Donald Knuth went so far as to claim that all of calculus could be taught without limits! Quoting from [1]:
"Students will be motivated to use O notation for two important reasons. First, it significantly simplifies calculations because it allows us to be sloppy — but in a satisfactorily controlled way. Second, it appears in the power series calculations of symbolic algebra systems like Maple and Mathematica, which today’s students will surely be using.
For more than 20 years I have dreamed of writing a calculus text entitled O Calculus, in which the subject would be taught along the lines sketched above."
[1] http://micromath.wordpress.com/2008/04/14/donald-knuth-calcu...
Here's the definition: if f and g are functions (let's say real-valued functions defined on the positive reals), then we say that f is big O of g, written f = O(g), if there exists a real number y and a real number K, K > 0, such that
f(x) <= K * g(x)
for every x > y.If that makes sense, then done.
Else:
The first thing to do when meeting any mathematical definition that you don't understand is to throw away parts of the definition until you do understand it, then add them back in one by one. In this case, let's forget about the constant.
New definition: For functions f, g, f is blorb of g, denoted f = blorb(g), if there is a y such that
f(x) <= g(x)
for every x > y."f is blorb of g" actually just means that there comes a point after which g is never smaller than f. This gives us the first ingredient of big O: we are concerned only with asymptotic behavior. f could take on immense values for small x and still be O(g) as long as f eventually becomes always smaller than g.
The reason for caring about asymptotic behavior is that we often don't care about the time complexity of an algorithm for very small problem sizes. Even the traveling salesman problem is solvable on Raspberry Pi for very small problem sizes.
Okay, I hope we understand the above definition. Now we add the constant back into the fold and see if we can make sense of it. From what I can see, the constant is there for computer scientists who want to paint with broader strokes. There can be a huge practical difference between f1(n) = 2n and f2(n) = 2000n (the difference between a computation taking a day and taking 3 years), but they're both O(n) because complexity theorists are more concerned with O(n^2) versus O(2^n) than they are with O(n) versus O(5n). (Also could be because in practice algorithms with wildly varying constant factors out in front are rarely seen?)
For an alternative to big O notation, you should check out Sedgewick and Wayne's Algorithms, 4th ed. They use something they call "tilde notation" which preserves the leading constant factor. (See: http://introcs.cs.princeton.edu/java/41analysis/)
The main reason is that you want a result that does not depend on small implementation details, i.e. is consistent across programing languages and CPU architectures.
Things as simple as larger cache size or a slightly better hashing function in a dict can increase the running speed of a program by a constant factor.
Second, talking about O(g(n)) does not imply that the time complexity being discussed is the worst-case (or any other case) time complexity. One could for example say that the algorithm A's best-case time complexity is in O(n), and it's worst-case time complexity is in O(n^2).
Like most simplifications, it's not entirely correct.
Which is why I like the comments section of HN - where I can learn more about the concept by observing how a wide variety of people explain it (and in the process correct the errors of the original article).