Number of single cycle components in an undirected graph - GeeksforGeeks

CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems




WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


ML & Data Science
                        


Machine Learning

Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


School Learning
                        


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


DSA Live Classes


System Design


Java Backend Development


Full Stack LIVE


Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


DSA- Self Paced


SDE Theory


Must-Do Coding Questions


Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Competitive Programming


Data Structures with C++


Data Science


Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


DSA- Self Paced


CIP


JAVA / Python / C++


Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


School Guide


Python Programming


Learn To Make Apps


Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Searching Algorithms


Sorting Algorithms


Graph Algorithms


Pattern Searching


Geometric Algorithms


Mathematical


Bitwise Algorithms


Randomized Algorithms


Greedy Algorithms


Dynamic Programming


Divide and Conquer


Backtracking


Branch and Bound


All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Asymptotic Analysis


Worst, Average and Best Cases


Asymptotic Notations


Little o and little omega notations


Lower and Upper Bound Theory


Analysis of Loops


Solving Recurrences


Amortized Analysis


What does 'Space Complexity' mean ?


Pseudo-polynomial Algorithms


Polynomial Time Approximation Scheme


A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Arrays


Linked List


Stack


Queue


Binary Tree


Binary Search Tree


Heap


Hashing


Graph


Advanced Data Structure


Matrix


Strings


All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Company Preparation


Top Topics


Practice Company Questions


Interview Experiences


Experienced Interviews


Internship Interviews


Competititve Programming


Design Patterns


System Design Tutorial


Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


C


C++


Java


Python


C#


JavaScript


jQuery


SQL


PHP


Scala


Perl


Go Language


HTML


CSS


Kotlin


ML & Data Science
                        


Machine Learning

Data Science


Machine Learning


Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


Mathematics


Operating System


DBMS


Computer Networks


Computer Organization and Architecture


Theory of Computation


Compiler Design


Digital Logic


Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


GATE Computer Science Notes


Last Minute Notes


GATE CS Solved Papers


GATE CS Original Papers and Official Keys


GATE 2021 Dates


GATE CS 2021 Syllabus


Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


HTML


CSS


JavaScript


AngularJS


ReactJS


NodeJS


Bootstrap


jQuery


PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


Software Design Patterns


System Design Tutorial


School Learning
                        


School Programming


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Number System


Algebra


Trigonometry


Statistics


Probability


Geometry


Mensuration


Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


ISRO CS Original Papers and Official Keys


ISRO CS Solved Papers


ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


UGC NET CS Notes Paper II


UGC NET CS Notes Paper III


UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Campus Ambassador Program


School Ambassador Program


Project


Geek of the Month


Campus Geek of the Month


Placement Course


Competititve Programming


Testimonials


Student Chapter


Geek on the Top


Internship


Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Top 50 Array Problems


Top 50 String Problems


Top 50 Tree Problems


Top 50 Graph Problems


Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Apply for Jobs


Post a Job


JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


All DSA Problems


Problem of the Day


Interview Series: Weekly Contests


Bi-Wizard Coding: School Contests


Contests and Events


Practice SDE Sheet

GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Graph and its representations
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Topological Sorting
Detect Cycle in a Directed Graph
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Detect cycle in an undirected graph
Strongly Connected Components
Find the number of islands | Set 1 (Using DFS)
Minimum number of swaps required to sort an array
Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8
Ford-Fulkerson Algorithm for Maximum Flow Problem
Check whether a given graph is Bipartite or not
Shortest path in an unweighted graph
Iterative Depth First Traversal of Graph
Traveling Salesman Problem (TSP) Implementation
Connected Components in an undirected graph
Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)
Print all paths from a given source to a destination
Applications of Depth First Search
m Coloring Problem | Backtracking-5
Dijkstra's Shortest Path Algorithm using priority_queue of STL
Hamiltonian Cycle | Backtracking-6
Kahn's algorithm for Topological Sorting
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Graph and its representations
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Topological Sorting
Detect Cycle in a Directed Graph
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Detect cycle in an undirected graph
Strongly Connected Components
Find the number of islands | Set 1 (Using DFS)
Minimum number of swaps required to sort an array
Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8
Ford-Fulkerson Algorithm for Maximum Flow Problem
Check whether a given graph is Bipartite or not
Shortest path in an unweighted graph
Iterative Depth First Traversal of Graph
Traveling Salesman Problem (TSP) Implementation
Connected Components in an undirected graph
Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)
Print all paths from a given source to a destination
Applications of Depth First Search
m Coloring Problem | Backtracking-5
Dijkstra's Shortest Path Algorithm using priority_queue of STL
Hamiltonian Cycle | Backtracking-6
Kahn's algorithm for Topological Sorting
Difficulty Level :
Medium
Given a set of ‘n’ vertices and ‘m’ edges of an undirected simple graph (no parallel edges and no self-loop), find the number of single-cycle-components present in the graph. A single-cyclic-component is a graph of n nodes containing a single cycle through all nodes of the component.Example:  
Let us consider the following graph with 15 vertices.
Input: V = 15, E = 14
       1 10  // edge 1
       1 5   // edge 2
       5 10  // edge 3
       2 9   // ..
       9 15  // ..
       2 15  // ..
       2 12  // ..
       12 15 // ..
       13 8  // ..
       6 14  // ..
       14 3  // ..
       3 7   // ..
       7 11  // edge 13
       11 6  // edge 14
Output :2
In the above-mentioned example, the two 
single-cyclic-components are composed of 
vertices (1, 10, 5) and (6, 11, 7, 3, 14) 
respectively.
Now we can easily see that a single-cycle-component is a connected component where every vertex has the degree as two. Therefore, in order to solve this problem we first identify all the connected components of the disconnected graph. For this, we use depth-first search algorithm. For the DFS algorithm to work, it is required to maintain an array ‘found’ to keep an account of all the vertices that have been discovered by the recursive function DFS. Once all the elements of a particular connected component are discovered (like vertices(9, 2, 15, 12) form a connected graph component ), we check if all the vertices in the component are having the degree equal to two. If yes, we increase the counter variable ‘count’ which denotes the number of single-cycle-components found in the given graph. To keep an account of the component we are presently dealing with, we may use a vector array ‘curr_graph’ as well. 
C++
Java
Python3
C#
Javascript
// CPP program to find single cycle components// in a graph.#include <bits/stdc++.h>using namespace std; const int N = 100000; // degree of all the verticesint degree[N]; // to keep track of all the vertices covered// till nowbool found[N]; // all the vertices in a particular// connected component of the graphvector<int> curr_graph; // adjacency listvector<int> adj_list[N]; // depth-first traversal to identify all the// nodes in a particular connected graph// componentvoid DFS(int v){    found[v] = true;    curr_graph.push_back(v);    for (int it : adj_list[v])        if (!found[it])            DFS(it);} // function to add an edge in the graphvoid addEdge(vector<int> adj_list[N], int src,             int dest){    // for index decrement both src and dest.    src--, dest--;    adj_list[src].push_back(dest);    adj_list[dest].push_back(src);    degree[src]++;    degree[dest]++;} int countSingleCycles(int n, int m){    // count of cycle graph components    int count = 0;    for (int i = 0; i < n; ++i) {        if (!found[i]) {            curr_graph.clear();            DFS(i);             // traversing the nodes of the            // current graph component            int flag = 1;            for (int v : curr_graph) {                if (degree[v] == 2)                    continue;                else {                    flag = 0;                    break;                }            }            if (flag == 1) {                count++;            }        }    }    return(count);} int main(){    // n->number of vertices    // m->number of edges    int n = 15, m = 14;    addEdge(adj_list, 1, 10);    addEdge(adj_list, 1, 5);    addEdge(adj_list, 5, 10);    addEdge(adj_list, 2, 9);    addEdge(adj_list, 9, 15);    addEdge(adj_list, 2, 15);    addEdge(adj_list, 2, 12);    addEdge(adj_list, 12, 15);    addEdge(adj_list, 13, 8);    addEdge(adj_list, 6, 14);    addEdge(adj_list, 14, 3);    addEdge(adj_list, 3, 7);    addEdge(adj_list, 7, 11);    addEdge(adj_list, 11, 6);     cout << countSingleCycles(n, m);     return 0;}
// Java program to find single cycle components// in a graph.import java.util.*; class GFG{ static int N = 100000; // degree of all the verticesstatic int degree[] = new int[N]; // to keep track of all the vertices covered// till nowstatic boolean found[] = new boolean[N]; // all the vertices in a particular// connected component of the graphstatic Vector<Integer> curr_graph = new Vector<Integer>(); // adjacency liststatic Vector<Vector<Integer>> adj_list = new Vector<Vector<Integer>>(); // depth-first traversal to identify all the// nodes in a particular connected graph// componentstatic void DFS(int v){    found[v] = true;    curr_graph.add(v);    for (int it = 0 ;it < adj_list.get(v).size(); it++)        if (!found[adj_list.get(v).get(it)])            DFS(adj_list.get(v).get(it));} // function to add an edge in the graphstatic void addEdge( int src,int dest){    // for index decrement both src and dest.    src--; dest--;    adj_list.get(src).add(dest);    adj_list.get(dest).add(src);    degree[src]++;    degree[dest]++;} static int countSingleCycles(int n, int m){    // count of cycle graph components    int count = 0;    for (int i = 0; i < n; ++i)    {         if (!found[i])        {            curr_graph.clear();                         DFS(i);             // traversing the nodes of the            // current graph component            int flag = 1;            for (int v = 0 ; v < curr_graph.size(); v++)            {                if (degree[curr_graph.get(v)] == 2)                    continue;                else                {                    flag = 0;                    break;                }            }            if (flag == 1)            {                count++;            }        }    }    return(count);} // Driver codepublic static void main(String args[]){         for(int i = 0; i < N + 1; i++)    adj_list.add(new Vector<Integer>());         // n->number of vertices    // m->number of edges    int n = 15, m = 14;    addEdge( 1, 10);    addEdge( 1, 5);    addEdge( 5, 10);    addEdge( 2, 9);    addEdge( 9, 15);    addEdge( 2, 15);    addEdge( 2, 12);    addEdge( 12, 15);    addEdge( 13, 8);    addEdge( 6, 14);    addEdge( 14, 3);    addEdge( 3, 7);    addEdge( 7, 11);    addEdge( 11, 6);          System.out.println(countSingleCycles(n, m));}} // This code is contributed by Arnab Kundu
# Python3 program to find single# cycle components in a graph.N = 100000 # degree of all the verticesdegree = [0] * N # to keep track of all the# vertices covered till nowfound = [None] * N # All the vertices in a particular# connected component of the graphcurr_graph = [] # adjacency listadj_list = [[] for i in range(N)] # depth-first traversal to identify# all the nodes in a particular# connected graph componentdef DFS(v):     found[v] = True    curr_graph.append(v)         for it in adj_list[v]:        if not found[it]:            DFS(it) # function to add an edge in the graphdef addEdge(adj_list, src, dest):     # for index decrement both src and dest.    src, dest = src - 1, dest - 1    adj_list[src].append(dest)    adj_list[dest].append(src)    degree[src] += 1    degree[dest] += 1 def countSingleCycles(n, m):     # count of cycle graph components    count = 0    for i in range(0, n):        if not found[i]:            curr_graph.clear()            DFS(i)             # traversing the nodes of the            # current graph component            flag = 1            for v in curr_graph:                if degree[v] == 2:                    continue                else:                    flag = 0                    break                             if flag == 1:                count += 1         return count # Driver Codeif __name__ == "__main__":     # n->number of vertices    # m->number of edges    n, m = 15, 14    addEdge(adj_list, 1, 10)    addEdge(adj_list, 1, 5)    addEdge(adj_list, 5, 10)    addEdge(adj_list, 2, 9)    addEdge(adj_list, 9, 15)    addEdge(adj_list, 2, 15)    addEdge(adj_list, 2, 12)    addEdge(adj_list, 12, 15)    addEdge(adj_list, 13, 8)    addEdge(adj_list, 6, 14)    addEdge(adj_list, 14, 3)    addEdge(adj_list, 3, 7)    addEdge(adj_list, 7, 11)    addEdge(adj_list, 11, 6)     print(countSingleCycles(n, m)) # This code is contributed by Rituraj Jain
// C# program to find single cycle components// in a graph.using System;using System.Collections.Generic;     class GFG{static int N = 100000; // degree of all the verticesstatic int []degree = new int[N]; // to keep track of all the vertices covered// till nowstatic bool []found = new bool[N]; // all the vertices in a particular// connected component of the graphstatic List<int> curr_graph = new List<int>(); // adjacency liststatic List<List<int>> adj_list = new List<List<int>>(); // depth-first traversal to identify all the// nodes in a particular connected graph// componentstatic void DFS(int v){    found[v] = true;    curr_graph.Add(v);    for (int it = 0; it < adj_list[v].Count; it++)        if (!found[adj_list[v][it]])            DFS(adj_list[v][it]);} // function to add an edge in the graphstatic void addEdge(int src,int dest){    // for index decrement both src and dest.    src--; dest--;    adj_list[src].Add(dest);    adj_list[dest].Add(src);    degree[src]++;    degree[dest]++;} static int countSingleCycles(int n, int m){    // count of cycle graph components    int count = 0;    for (int i = 0; i < n; ++i)    {        if (!found[i])        {            curr_graph.Clear();                         DFS(i);             // traversing the nodes of the            // current graph component            int flag = 1;            for (int v = 0 ; v < curr_graph.Count; v++)            {                if (degree[curr_graph[v]] == 2)                    continue;                else                {                    flag = 0;                    break;                }            }            if (flag == 1)            {                count++;            }        }    }    return(count);} // Driver codepublic static void Main(String []args){    for(int i = 0; i < N + 1; i++)    adj_list.Add(new List<int>());         // n->number of vertices    // m->number of edges    int n = 15, m = 14;    addEdge(1, 10);    addEdge(1, 5);    addEdge(5, 10);    addEdge(2, 9);    addEdge(9, 15);    addEdge(2, 15);    addEdge(2, 12);    addEdge(12, 15);    addEdge(13, 8);    addEdge(6, 14);    addEdge(14, 3);    addEdge(3, 7);    addEdge(7, 11);    addEdge(11, 6);         Console.WriteLine(countSingleCycles(n, m));}} // This code is contributed by PrinciRaj1992
<script> // JavaScript program to find single cycle components// in a graph. let N = 100000; // degree of all the verticeslet degree=new Array(N);for(let i=0;i<N;i++)    degree[i]=0;// to keep track of all the vertices covered// till nowlet found=new Array(N);for(let i=0;i<N;i++)    found[i]=0; // all the vertices in a particular// connected component of the graphlet curr_graph = []; // adjacency listlet adj_list = []; // depth-first traversal to identify all the// nodes in a particular connected graph// componentfunction DFS(v){    found[v] = true;    curr_graph.push(v);    for (let it = 0 ;it < adj_list[v].length; it++)        if (!found[adj_list[v][it]])            DFS(adj_list[v][it]);} // function to add an edge in the graphfunction addEdge(src,dest){    // for index decrement both src and dest.    src--; dest--;    adj_list[src].push(dest);    adj_list[dest].push(src);    degree[src]++;    degree[dest]++;} function countSingleCycles(n,m){    // count of cycle graph components    let count = 0;    for (let i = 0; i < n; ++i)    {           if (!found[i])        {            curr_graph=[];                           DFS(i);               // traversing the nodes of the            // current graph component            let flag = 1;            for (let v = 0 ; v < curr_graph.length; v++)            {                if (degree[curr_graph[v]] == 2)                    continue;                else                {                    flag = 0;                    break;                }            }            if (flag == 1)            {                count++;            }        }    }    return(count);} // Driver codefor(let i = 0; i < N + 1; i++)    adj_list.push([]); // n->number of vertices// m->number of edgeslet n = 15, m = 14;addEdge( 1, 10);addEdge( 1, 5);addEdge( 5, 10);addEdge( 2, 9);addEdge( 9, 15);addEdge( 2, 15);addEdge( 2, 12);addEdge( 12, 15);addEdge( 13, 8);addEdge( 6, 14);addEdge( 14, 3);addEdge( 3, 7);addEdge( 7, 11);addEdge( 11, 6);  document.write(countSingleCycles(n, m)); // This code is contributed by avanitrachhadiya2155 </script>
2
 
Hence, total number of cycle graph component is found. 
PiyushKumar
rituraj_jain
andrew1234
princiraj1992
avanitrachhadiya2155
DFS
graph-connectivity
graph-cycle
Graph
Greedy
Greedy
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Longest Path in a Directed Acyclic Graph
Best First Search (Informed Search)
Graph Coloring | Set 2 (Greedy Algorithm)
Maximum Bipartite Matching
Graph Coloring | Set 1 (Introduction and Applications)
Program for array rotation
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3
Coin Change | DP-7
Activity Selection Problem | Greedy Algo-1