So when someone asks you to give a O(n) or a O(nlogn) algorithm to compute something, how do you know what to answer? It seems the only way of being able to answer this sort of question is knowing the time complexities of various algorithms beforehand, rather than thinking up something on the spot. Am I correct in assuming this?
Let's use T(n) as the total time in function of the input size n , and t as the time complexity taken by a statement or group of statements. T(n) = t(statement1) + t(statement2) + ... + t(statementN); If each statement executes a basic operation, we can say it takes constant time O(1) .
To express the time complexity of an algorithm, we use something called the “Big O notation”. The Big O notation is a language we use to describe the time complexity of an algorithm.
Any loop will take up as much space as the length of the item we are looping over. In this case we need to loop through the array to find out the total of all of the values in the array, thus our space complexity will be O(n) or linear where n is the number of elements in our array.
simple cases are:
Iteration along the list - O(n)
Single binary or tree operation - O(log n) (which means insertion of n elements into the tree is n log n)
Hashtable operation - O(1)
NP complete problem (here you need some experience to develop an intuition) - exponential time in general (in practice for many problems an efficient heuristics can be applied)
for graph with E edges and V vertices the complexity is F(E,V) depending on the nature of the algorithm and density of the graph. E+V for good DFS/BFS.
Almost every algorithm can be partitioned into the set of above (or similar) small blocks. When blocks are combined recursively, like A-includes-B, the complexity multiplies, when blocks follow each other, like A-then-B, the complexity is max(complexity A, complexity B)
You are right, you should know the time complexities for different algorithms to know this. You should know the time complexities for sorting, for finding items in a dictionary, in a hash table, union find, flow graphs, DFS, BFS, minimum spanning trees, etc. These are the basics.
Introduction to Algorithms should have you well covered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With