Detect Cycle in an Undirected Connected Graph (DFS)
JavaScript
medium
30 mins
You receive the graph as an array of edge pairs edges, where each pair [u, v] represents a bidirectional connection between nodes u and v. Implement hasCycle(edges) that:
- Builds an adjacency list from those pairs.
- Starts DFS from node 0 only.
- Returns true as soon as DFS encounters a neighbor that is visited and not the immediate parent.
Examples
Input: edges = [[0, 1], [1, 2]] Output: false
Input: edges = [[0, 1], [1, 2], [2, 0]] Output: true
Constraints
- Nodes are assumed to be integers that can act as object keys.
- Edges should always include the component that contains node 0; the function never explores other components.
- Inputs are expected to be well-formed arrays of two-item arrays; no explicit validation is performed.
- Self-loops or malformed inputs can lead to unexpected results because no guards are present.
Function Signature
function hasCycle(edges) { // Your code here }
Test Cases
- Base cases: [], single edge [ [0, 1] ]
- Triangle: [ [4,3], [4,5], [3,5] ] -> true
- Disconnected graphs with and without cycles
- Graphs anchored at node 0 that either stay acyclic or form a cycle
- Cases where the first DFS branch already hits a back edge
Companies:
amazon
microsoft
uber
adobe
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
