Tuesday, March 7, 2017

Big-O notation explained(Time Complexity)

1. So setting a counter to zero is a constant time operation.

total = 0;
==> O(1)



2. If it's 75, we do 75 operations. In mathematical terms, this means that the time it takes to do something increases linearly with its input. We use a variable to represent the size of the input, which everyone in the industry calls n. So the "loop over the list" function is O(n) where n represents the size of a_list.

for element in a_list:
==> O(n)

3. Checking whether an element is equal to 1 is an O(1) operation

if element == 1:
==> O(1)


4. Next, we increment total by 1. This is like setting total to zero (but you have to do addition first). Addition of one, like equality, is also constant time.

total += 1
==> O(1)

So, For all 4,
--------------
(O(1) + O(n) * (O(1) + O(1))
                         ^^^^^^^^^^^^
(O(2n) + O(1))


In big O, we only care about the biggest "term" here. "Term" is the mathematical word that means "portion of an algebraic statement".

in calculating Big-O, we're only interested in the biggest term: O(2n). Because Big-O only deals in approximation, we drop the 2 entirely, because the difference between 2n and n isn't fundamentally different.


Resource Link:
==============
compare the graph of x^2 vs 2x vs x.

  1. http://www.wolframalpha.com/input/?i=plot+x%5E2,+x%5E3,+x%5E4+from+x%3D0+to+10  
  2. https://justin.abrah.ms/computer-science/big-o-notation-explained.html


No comments:

Post a Comment