Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big-O: How do you know what algorithm to give for a specific time complexity?

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?

like image 209
Parth Avatar asked Jul 18 '10 00:07

Parth


People also ask

How do you find the time complexity of a specific algorithm?

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) .

Which algorithm is used for time complexity?

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.

What is the space complexity of your algorithm in terms of Big O?

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.


2 Answers

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)

like image 191
bobah Avatar answered Nov 15 '22 08:11

bobah


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.

like image 33
Amir Rachum Avatar answered Nov 15 '22 06:11

Amir Rachum