Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coming up with an algorithm in O(n)

Here is the problem to solve:

N dwarves make m statements about who is taller than who (for example: Jason < Tim, Burton < Jason etc.), but some dwarves could lie about the order and give us the wrong statement, so its our job to check if it's possible to order the dwarves by their size accordingly. The result is either "Possible" or "Impossible" in case a dwarf lied.

So far I understand the idea of imagining a directed graph of the dwarves (with a class for the dwarf) which should tells us the name of the dwarf himself and the names of the dwarves who are taller than him. Since this is supposed to be a spanning tree, the result should be "Impossible" if the graph contains a cycle.

How can I manage this in O(n) runtime? I already tried some stuff with a lot of for-loop and recursion, but that would either not be suitable or take too much time when handling a large-sized case of this problem. I was later told to rather figure out an algorithm with O(n) runtime.

I would like to know how I should change my way of thinking when I am supposed to solve a problem in a certain runtime.

like image 934
JinseiNagai Avatar asked Jan 25 '17 21:01

JinseiNagai


People also ask

What is O n In algorithm?

O(N) describes an algorithm whose performance will grow linearly and in direct proportion to the size of the input data set.

What is the best O notation for your algorithm?

Big O notation ranks an algorithms' efficiency Same goes for the “6” in 6n^4, actually. Therefore, this function would have an order growth rate, or a “big O” rating, of O(n^4) . When looking at many of the most commonly used sorting algorithms, the rating of O(n log n) in general is the best that can be achieved.

What are o1 algorithms?

O(1) describes algorithms that take the same amount of time to compute regardless of the input size. For instance, if a function takes the same time to process ten elements and 1 million items, then we say that it has a constant growth rate or O(1) .


1 Answers

You are right in using a Directed Graph as this is a Topological Sort problem. The key point is that you may get a number of start nodes rather than one single starting point. Hence even if you want O(n + m) time complexity, you will also need O(n + m) space.

The link mentions a Kahn's algorithm which can detect cycles. Cycle detection can be performed using a simple DFS traversal as mentioned in the same link. That is also an O(n + m) algorithm.

like image 188
user1952500 Avatar answered Oct 05 '22 20:10

user1952500