← Microsoft Interview Insights

Microsoft·Software Engineer·Technical Phone Screen·Intermediate

Intermediate
May 2026

Summary

Microsoft coding interview with a graph theory problem. Nothing too wild but the BFS angle took me a minute to fully work through.

Questions Asked (1)

Q1

Given a bidirectional graph with n vertices (labeled 0 to n-1) and a list of edges, find the length of the shortest cycle. Return -1 if no cycle exists.

Algorithms & Data Structures
Author's notes

My first instinct was DFS and I started going down that path before catching myself.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by clarifying the problem constraints and edge cases, then propose a BFS-based solution that finds the shortest cycle by exploring each vertex as a potential cycle start. Explain how to avoid counting the same edge back and forth, and analyze the time complexity.

Pro tip: Mention that for unweighted graphs, BFS from each vertex gives the shortest cycle in O(n*(n+m)) time, but you can optimize by only considering vertices with degree ≥ 2 and stopping early if a cycle of length 3 is found.

1. Clarify requirements and edge cases

Ask about graph properties (connected? simple? self-loops? multi-edges?) and confirm return value for no cycle. Discuss constraints on n and m to guide algorithm choice.

2. Choose algorithm and justify

Propose BFS from each vertex to find shortest cycle, explaining why BFS works for unweighted graphs. Alternatively, mention DFS with parent tracking but note BFS is simpler for shortest path.

3. Detail BFS approach

For each vertex s, run BFS, tracking parent to avoid immediate backtracking. When encountering a visited vertex not parent, a cycle is found; compute its length and update minimum.

4. Analyze complexity and optimize

State time complexity O(n*(n+m)) and space O(n). Mention optimizations: skip vertices with degree < 2, stop if cycle length 3 found, and consider only vertices with smallest degree.

5. Test with examples

Walk through a simple graph (e.g., triangle) and a graph with no cycle to verify correctness. Discuss handling of disconnected graphs.

Key Points to Mention

  • BFS is optimal for unweighted shortest path due to level-order traversal.
  • Avoid counting the same edge twice by tracking parent in BFS.
  • Time complexity O(n*(n+m)) and space O(n).
  • Edge cases: no cycle, self-loops, multi-edges, disconnected graph.
  • Optimization: early termination if cycle of length 3 is found.
  • Alternative: for dense graphs, consider matrix multiplication or other methods but BFS is standard.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.