r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

188

u/famrob Apr 05 '22

Big O. I’m quite far in the CS program at my school but the professor who tried to teach me big O was just absolutely horrible at it, so it went in one ear and out the other

166

u/tzaeru Apr 05 '22 edited Apr 05 '22

Big O basically tells how much time or space a function needs when its input grows in size.

For example, consider this algorithm:

function(int n):
    counter = 0
    for (i = 0; i < n; i++)
         for (j = 0; j < n; j++)
             counter++
    return counter

If n is 1, what's the number returned? It's 1*1 = 1. There was 1 increment operation done.

If n is 4, what's the number returned? It's 4*4 = 16. There were 16 increment operations done.

So you see the algorithm's time complexity grows by n^ 2. Big O notation is a way of expressing this; we can say that the time complexity is O(n2 ).

You can simply get the time complexity by counting the number of operations in the function and comparing how that number changes depending on the size of the input.

O(log n) is one very common time complexity and one example of an algorithm with O(log n) time complexity is searching a sorted array with binary search. The reason it's log n is that in each step, binary search splits the search space in two; so with input with size of 8 there are at most 4->2->1 or 3 steps, while with input size of 16 there's at most 8->4->2->1 or 4 steps.

4/3 = 1.33.. and log(16)/log(8) = 1.33..

94

u/Rote515 Apr 05 '22

Although this comment is true, i don’t think it gets to the heart of BigO, the most important part of bigO is that it’s a time complexity estimation more than an exact time complexity which your examples do not show. For example a 3N + 2N + 2N2 algorithm has a bigO of N2 as we drop the constants and only use the fastest growing term, because as N gets large it ends up being the only term we care about from a complexity point of view.

24

u/XilamBalam Apr 05 '22

Yes, it's looking how the function "behaves at infinity" (asymptotic behaviour).

→ More replies (2)

5

u/MaxwellCE Apr 06 '22

What if the algorithm is N² + N³? Could we say that has a big O of N³, or is the N² component non-negligible?

10

u/Rote515 Apr 06 '22

BigO only ever cares about the fastest growing term, so n2 + n3 would be N3 significance doesn’t matter, consider n = 20 in the above algorithm, n2 = 400 n3 = 8000 at that point n is negligible already, now imagine n=100 or n=1000 a larger power always makes the smaller power insignificant at any non trivial n

2

u/[deleted] Apr 06 '22

Infinite limits have entered the chat

→ More replies (1)

2

u/__Fred Apr 06 '22 edited Apr 06 '22

/u/famrob

To add to that: Technically O(n²) is a set. It's the set of all functions for which this is true:

There is exists a factor C and a threshold for which all x thereafter: f(x) ≤ C * x²


For example, if you have this Python function:

def combinations(list1, list2):
    result = []
    for e1 in list1:
        for e2 in list2:
            result.append(e1 + e2)
    return result

How long does it take to run? Well, we can't know for sure. If each of those operations always took the same time (which isn't true), it would take the running time of

  • result = []

    • for e1 in list1 * the length of list1

    • for e2 in list2 * len(list1) * len(list2)

    • result.append(e1 + e2) * len(list1) * len(list2)

    • the running time of return result

The the function "t" that gives the running time of combinations has to have two parameters "n" - len(list1) and "m" - len(list2).

t(n,m) = a + b * n + c * n * m

Everything clear so far? "c" would be the time for for e2 in list2: result.append(e1 + e2), for example.

For simplicity sake, we can just assume that both lists have the same length. Then the formula becomes this:

t(n) = a + b * n + c * n²

Is this function in the set of O(n²)? Can you choose a factor C and a threshold n'?

For all n > n': t(n) ≤ C * n²
For all n > a: a + b * n + c * n² ≤ (a+b+c) * n²

(Seems correct. I'm not sure.)


Anyway... Basically, what you normally do if you have a sum of multiple factors, is look at the factor that would grow the fastest. "c * n²" grows faster than "b * n". No matter how large b is, if you took a big enough n, "c * n²" would be larger than "b * n". "dn" would grow even faster than n².

So, if you know that "c * n²" is the dominant factor in your time function, than you can already say that the function is in (or colloquially is) O(n²).

If you have one loop that is dependent on the input, you typically have O(n) and if you have a nested loop, it's typically O(n²).

If we want to know whether an algorithm is good, we don't need the exact execution time function, we just need the complexity class.

If I'm not mistaken technically O(n) is a subset of O(n²), but don't try to write that the time complexity of insertion-sort is O(n³) in an exam. That's not what they mean.

Wikipedia for further details

1

u/corner_guy0 Apr 06 '22

Great explanation brother and also Happy Cake Day!

57

u/Rote515 Apr 05 '22 edited Apr 05 '22

BigO is super straightforward if you have a decent understanding of algebra. The general gist of it is that in computer science we only really care about the fastest growing term for time complexity, so for example if I have a function that is solved in the following number of steps. N+N2 where N is the size of the input, the the BigO time complexity is N2 since that’s the fastest growing term. The reason we care only about the fastest growing term is because when N gets very large that’s the only term that will really matter. For instance in the above equation if our input N is a list of 10,000 integers, well 10,000 operations is trivial for a modern processor, but 10,000*10,000 is not, that can take actual time to complete.

There’s a bit more to it than that, but that is the basics of BigO

Edit: one last thing, BigO is very useful but it doesn’t tell the whole story of time complexity, it’s a good way to understand the basics as N gets very large, but it can be misleading in certain algorithms. For example the equation 10000000n + n2 for the number of steps to complete an algorithm is still O(n2) time complexity, but because the first term has a super large constant it’s till likely not the most efficient solution depending on what you’re solving, there might be a case where an algorithmic n + n3 is better if n never gets very large for example even thought it’s O(n3) which is generally a very bad time complexity.

6

u/a_Delorean Apr 05 '22

Holy shit you explained this very well; thank you

2

u/[deleted] Apr 06 '22

Do you happen to have an example of when this could be applied in a real life situation?

5

u/Rote515 Apr 06 '22

Which part? Just bigO in general? Literally any algorithm you ever write for any purpose can have bigO applied to it, it’s just a way of monitoring the steps it takes your algorithm to complete. Why it’s useful? I’m at a bar at the moment so no time/desire to type this out on my phone :D but take for example 2 unsorted arrays of size N integers, how would you test to see if those arrays held the same values? As in how would you test that {5,4,3,2,1} == {1,2,3,4,5}? There’s two easy ways off the top of my semi-drunk head to do that, you could do it using 2 loops, checking each element of the first array against the second array. It’s incredibly simple to write and has virtually no setup work. But it’s super inefficient when N is very large, it’s an N2 algorithm. The other way is you could sort each array first then check it using a single loop to make sure all indexes of the array match, that way is NlogN + NlogN + N simplified as 2NLogN + N which in BigO is O(NlogN), there’s a ton of setup work and data manipulation that increases both space and time complexity, but as N gets very large the second algorithm will be much faster.

You can write that yourself and test if you want, and if you really want to see it and can’t figure it out I’ll write it either tomorrow or Thursday for you.

That is an example that’s similar in concept to many you’ll run into in the real world, I just wrote one that manipulated data to take a list of charges and place them into an object where the charges are grouped by each customer. The algorithm I fixed was N2 time and mine was NlogN made a huge difference in time when N started getting large.

0

u/[deleted] Apr 06 '22

Hm interesting, I get the purpose of the principle. Just seems like it’s based on getting initial bad data. A good SQL statement and maybe using a little bit of LINQ would eliminate the need for this concept.

→ More replies (1)

2

u/[deleted] Apr 06 '22

I still don't understand this and I work as a programmer. I can never visualise what becomes N or when N is to the power of 2, etc.

Hello imposter syndrome.

11

u/AlSweigart Author: ATBS Apr 05 '22

I always recommend Ned Batchelder's 2018 PyCon talk How Code Slows as Data Grows to explain big O in technical-but-approachable terms in under 30 minutes.

6

u/Marvsdd01 Apr 05 '22 edited Apr 05 '22

I'm not that good on explaining things, and I assume you're not asking "how to calculate an algorithm's memory or time complexity" - as Big O is directly related to that. So, in that case... When you ask "what is the Big O of an algorithm?" you are asking "how does my algorithm perform in the worst scenario possible?" If you think about a sorting algorithm, you can put the "worst case scenario" as the case where you try to sort a very large amount of numbers, for example. In this case, if this sorting algorithm would, for the sake of the explanation, have a Big O notation of O(n*log(n)) in terms of time spent running it, you're saying that the algorithm makes that amount of operations to complete the task of sorting an array. The "n" in the expression is a general representation of the size of the array, in this case. In most cases, you don't need an exact calculation of the algorithm's complexity, so we use an approximation.

Edit: spelling errors

5

u/Marvsdd01 Apr 05 '22 edited Apr 05 '22

Just so I can add a little more... Let's say you have two sorting algorithms: one performs at O(n2) in the worst case scenario, and other performs at O(n * log(n)). If you explode the size of the array you're sorting, then the difference between those two algorithms become very clear in terms of time spent sorting/number of operations needed to sort the array (as, mathematically, n2 is bigger than n * log(n)). That's the basic idea of using Big O notation (or any complexity notation, actually). If we want to check how two algorithms perform in terms of operations done or memory spent, it would be impractical (or sometimes impossible) to run these algorithms simultaneously and/or in the same running conditions to be able to compare them. Then we use a mathematical expression (complexity notation) so we can generalize performance of code in a way that we don't depend on computers to actually run it, and still can tell how this code is better or worse than another one.

Edit: the text became italic when I used an *

→ More replies (4)

1

u/MyBrainReallyHurts Apr 05 '22

First, you need a woman...

1

u/famrob Apr 05 '22

Lol. Surprisingly enough I have one

1

u/g0ing_postal Apr 06 '22

The way I always think of it is like this- if I double the problem space, how many more instructions are executed? What if I increase it by the same amount again, do it's 3x as large?

Big o is how the number of instructions scale to the problem space

So let's say when n=10, 10 lines are executed. When n=20, 100 lines are executed. When n =3, 1000 lines are executed, so the problem here is O(10n)

1

u/ExtraFig6 Apr 06 '22

A thing people miss about big O: it is only looking at the tendency as the input grows to infinity. If you know you'll only ever deal with 10 elements in your list, the big O is irrelevant.

1

u/green_meklar Apr 06 '22

Okay, first off this is confusing because big-O has a strict mathematical meaning and a different meaning that people tend to actually use. However, that part is relatively easy and not really the issue for wrapping your head around the basic concept.

The basic concept is, we want to know slow algorithms are, but in particular, we want to know how slow they are independently of what computer you use to run them. Obviously if you use a computer that is twice as fast, the algorithm will finish in half the time, but that's not very interesting from a CS perspective. What we want to know is how much all computers will slow down when we increase the size of the problem that we throw at the algorithm.

A simple example is finding whether a given value exists in an arbitrary list. You're given some value V and some list L. Because V might occur exactly once in L and at any position, you have no choice but to search all of L. (You might get lucky and find the value V somewhere right near the start of the list, in which case you can stop. But we are pessimistic and always assume that the algorithm takes as long as it possibly can, or in other words, that the input is chosen in a maximally evil manner to make the computer do more work. This is known as 'worst case' analysis.) Of course that takes half the time if your computer is twice as fast. But it also happens more slowly if L is longer. Usually we use the letter N to denote the 'size' of the problem (when the problem has just one size; some problems have sizes in multiple dimensions, but we don't need to worry about that just yet). So let's say that the length of L is N. If N becomes 3 times as large (that is, we feed in a list three times as long), then both our slow computer and our fast computer, and indeed any computer, will take 3 times as long to finish searching the array. We can finish faster by upgrading to a faster computer, but the algorithm itself that we have to use to solve the problem has this intrinsic property that it takes longer when the input is bigger. In particular, it takes longer exactly in proportion to the size of the list. We call this 'linear' growth.

Not all algorithms have linear growth. Imagine you need to find whether there are any two values in the list that are equal. The obvious approach (although not the fastest, as it turns out) is to iterate through the list, and for each item, iterate through the entire list again and check if there is any other item equal to it. This is slower because you're iterating through the list for every item in the list. If the list gets 3 times as long, the number of iterations you have to do goes up by 3 times twice, or 9 times in total. We call this 'quadratic' growth, where N gets multiplied by itself in order to describe the amount of work the computer does.

Notice how the amount of work actually done at each iteration is ignored in this analysis. We might have two algorithms that both iterate through the list and one does 5 times as much work as the other for each item in the list. But we can just find a computer that is 5 times faster, and then the slow algorithm will run just as fast on that computer as the fast algorithm runs on the slow computer. The 5 is therefore a 'constant' that we can throw away because we're specifically interested in how slow the algorithm is for all computers as we increase N, the input size.

Formally speaking, we say that the big-O notation takes some function F of N (and of other parameters, if the problem has sizes in multiple dimensions) and expresses that the growth of the algorithm's time requirement scales up no faster than C*F(N) for all sufficiently large values of N and some sufficiently large value C. So let's say we have the linear and quadratic algorithms outlined above. We can say that the linear algorithm is in O(N) and the quadratic algorithm is in O( N2 ). Even if the quadratic algorithm is being run by a super fast computer, by choosing large values of C and N we can show that the computer running the linear algorithm will tend to finish before the computer running the quadratic algorithm does. The faster computer cannot 'catch up' with the slower algorithm it's running, if we give it a large enough input. (And broadly, the big-O notation works for growing functions in general, it's just that expressing the running time of algorithms is the most common use case.)

The confusing part is that technically the linear algorithm is also in O( N2 ), and every higher big-O function like O( N100 ), O( 2N ), O(N!), etc. However, in common speech we tend not to say this; people expressing an algorithm's speed in big-O notation generally mean that the algorithm's worst-case running time scales up roughly similarly to the function they give, rather than just something less than it.

Conceptually speaking, in a typical environment with control flow based on loops and recursion, what we're counting in order to determine the algorithm's big-O running time are all the loop iterations and all the recursive calls. Simply add 1 for every loop iteration and 1 for every recursive call, and check how that sum grows. Everything else is considered a 'constant' and you can ignore it unless it somehow affects the conditions for the loops or recursion. I find that a lot of people miss this part and pay too much attention to irrelevant parts of the algorithm, so it's good to remember this.

1

u/[deleted] Apr 06 '22 edited Apr 06 '22

O(1) : This is the time complexity of simple operation. An if statement is O(1) for example.Think of O(1) as a single operation.

O(N) : This is the time complexity of iterative operations, where N is the amount of iterations. A simple for loop is most likely O(N) where N is the amount of loop cycles.

O(N^2): This is the time complexity of a loop within a loop (an inner loop), so lets say you have a loop that runs N times, with a loop inside it that runs X times. The time complexity would be N^2. You can see how this may run many more times than a O(N) loop.

If you have 2 inner loops that would be O(N^3) 3 would be (ON^4) you get the drift.

Now where big O gets interesting is things such as O(log N). O(log N) is faster than a standard O(N) loop but not a single operation like O(1). Something like a binary search tree is a great example of O(log N) its an optimized way of searching for something, in less time then O(N).

There are more complex time complexities like exponentials , factorials and polynomials . But I would say for the most part, if you can understand WHY time complexity is important and you can quickly gauge the time complexity of a solution you have understood it. Hope this helps

1

u/bharath208 Apr 07 '22

Here, I learn it is easy from this blog. Hope it might help you in understanding Big O Notation.

https://codelz.com/what-is-big-o-notation/