Home
Log in
DescriptionSubmissionsSolution
DescriptionSubmissionsSolution
Loading...

Log in to run or submit

n =
edges =

Codey

Practise coding problems, test your solutions and track your progress.

Explore

  • Problems
  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

© 2026 Codey. Personal learning project.

Solution
Updated: 2026-02-23

Idea

An undirected graph is a tree iff it’s connected and has no cycles.

Approach

  • If edges != n-1, immediately false.
  • Union-Find through edges; if any union fails (cycle), false.
  • At end, ensure exactly one component.

Why it works

Trees on n nodes have exactly n-1 edges and are connected; DSU detects cycles and connectivity.

Code
Loading...
Complexity
Time: O(E α(V))
Space: O(V)
Solution
Updated: 2026-02-23

Idea

An undirected graph is a tree iff it’s connected and has no cycles.

Approach

  • If edges != n-1, immediately false.
  • Union-Find through edges; if any union fails (cycle), false.
  • At end, ensure exactly one component.

Why it works

Trees on n nodes have exactly n-1 edges and are connected; DSU detects cycles and connectivity.

Code
Loading...
Complexity
Time: O(E α(V))
Space: O(V)