Count cycle in graph
Last updated: November 27, 2025
Quick Overview
Given a directed or undirected graph represented as an adjacency list, write a function to count the number of distinct cycles present in the graph. A cycle is defined as a path that starts and ends at the same vertex, with at least one edge traversed. The function should return an integer representing the total number of cycles found.
Bloomberg
November 27, 20252
12
3,564 solved
Given a directed or undirected graph represented as an adjacency list, write a function to count the number of distinct cycles present in the graph. A cycle is defined as a path that starts and ends at the same vertex, with at least one edge traversed. The function should return an integer representing the total number of cycles found.
Bloomberg uses this problem in the Technical Screen to evaluate your algorithmic thinking. They expect you to discuss multiple approaches, analyze trade-offs between them, and implement the optimal solution with clean, readable code.
What the Interviewer Expects
- Identify the correct data structure and algorithm for the problem
- Write clean, bug-free code with proper variable naming
- Analyze time and space complexity correctly
- Handle basic edge cases (empty input, single element)
- Communicate your thought process while coding
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- What is the worst-case input for your solution?
- How would your solution change if the input was sorted?
- Can you optimize the space complexity of your solution?
- How would you test this solution thoroughly?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Problem Analysis
To solve the problem of counting cycles in a graph, we can utilize Depth-First Search (DFS). This approach is appropriate because DFS can effectively explore all paths in the graph, allowing us to tra...
Approach
- Initialize a counter for cycles and a set to track visited nodes.
- For each node in the graph, if it has not been visited, initiate a DFS from that node.
- During the DFS, maintain a recursi...