Awesome q2a theme
0 votes

Give an algorithm that determines whether or not a given undirected graph G=(V,E) contains a cycle. Your algorithm should run in $O(V)$ time, independent of E.


If there’s a back edge, there’s a cycle. If there’s no back edge, there are only tree edges.  Hence, the graph is acyclic.
Thus, we can run DFS: if we find a back edge, there’s a cycle.

My doubt is how to manage this in $O(V)$ time ?

in Algorithms by (415 points) | 30 views
Already have that. You just give a little explanation about the complexity either from the link you provided or self explanation. Getting little difficulty to get that. Thank you.
In simple terms, undirected connected graph which doesn't have cycles, should be a tree.

For Tree, edges=nodes-1

So, your dfs = O(nodes+edges) =O(2nodes-1)= O(nodes)

If we ever see $|V |$ distinct edges, we must have seen a back edge because in an acyclic (undirected) forest, $|E| ≤ |V | − 1$.

@Shaik Masthan

Got it sir, Thankyou

Please log in or register to answer this question.

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
Welcome to GATE CSE Doubts, where you can ask questions and receive answers from other members of the community.
Top Users Jul 2020
  1. Shaik Masthan

    39 Points

  2. hiteshpujari

    9 Points

  3. fazin

    7 Points

  4. srestha

    7 Points

  5. gaurav2697

    6 Points

  6. Venkatesh Akhouri

    6 Points

  7. Meghana518

    6 Points

  8. beastincarnate

    6 Points

  9. athenahermes

    6 Points

  10. bittujash

    6 Points

7,561 questions
1,783 answers
90,494 users