DATA STRUCTURES PROGRAM • HEAPS, HASHING & DISJOINT SETS

Detect an Undirected Graph Cycle with DSU

Learn how to detect an undirected graph cycle with dsu using a clear C program.

IntermediateDSUCycle detectionEdges

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Cycle detected.

COMPLETE C PROGRAM

Complete C implementation

dsa-cycle-detection-dsu.c
Open in compiler
#include <stdio.h>

struct Edge { int source; int destination; };
int find(int parent[], int value)
{
    while (parent[value] != value) value = parent[value];
    return value;
}

int main(void)
{
    struct Edge edges[] = {{0, 1}, {1, 2}, {2, 0}};
    int parent[] = {0, 1, 2}, cycle = 0;
    for (int index = 0; index < 3; index++) {
        int first = find(parent, edges[index].source);
        int second = find(parent, edges[index].destination);
        if (first == second) { cycle = 1; break; }
        parent[second] = first;
    }
    puts(cycle ? "Cycle detected." : "No cycle.");
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Cycle detected.
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. An edge forms a cycle when both endpoints already share the same representative.
  3. Display the computed result.

An edge forms a cycle when both endpoints already share the same representative.

EFFICIENCY

Time and space complexity

Time complexity

O(n)

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.