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)