Skip to content
Home Interview Top 10 Graph Interview Problems: Patterns, Pitfalls & Solutions

Top 10 Graph Interview Problems: Patterns, Pitfalls & Solutions

Where developers are forged. · Structured learning · Free forever.
📍 Part of: Coding Patterns → Topic 5 of 17
Master the top 10 graph interview problems with deep pattern analysis, runnable Java code, edge cases, and the exact questions FAANG interviewers ask.
🔥 Advanced — solid Interview foundation required
In this tutorial, you'll learn
Master the top 10 graph interview problems with deep pattern analysis, runnable Java code, edge cases, and the exact questions FAANG interviewers ask.
  • You now understand that graph problems are often just 'Matrix or Adjacency List' puzzles in disguise.
  • You've implemented BFS for shortest paths and Kahn's Algorithm for topological sorting using io.thecodeforge standards.
  • The secret to graph interviews is choosing the right data structure (Queue vs. Stack vs. Priority Queue) for the traversal pattern.
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
Quick Answer

Imagine a city map. Every intersection is a dot, and every road connecting two intersections is a line. A graph is exactly that — dots (nodes) connected by lines (edges). Graph problems ask you things like: 'What's the shortest route from home to school?', 'Can I get from any city to any other city?', or 'Is there a road that, if it breaks, cuts two towns off from each other?' Every GPS app, social network, and package delivery system solves graph problems thousands of times per second.

Graph problems are the great filter of software engineering interviews. They appear in roughly 30% of FAANG-level coding rounds not because interviewers love theory, but because real systems — Google Maps, LinkedIn's friend-of-a-friend suggestions, Uber's dispatch engine, Kubernetes dependency resolution — are fundamentally graphs under the hood. If you can't navigate a graph, you can't reason about the systems that run the modern internet.

The challenge with graph interviews isn't memorizing algorithms. BFS and DFS are straightforward once you've seen them twice. The real difficulty is pattern recognition: knowing within 60 seconds whether a problem is a shortest-path problem, a cycle detection problem, a topological sort problem, or a connected-components problem — and then executing flawlessly under pressure without missing the edge cases that separate a 'hire' from a 'no hire'.

By the end of this article you'll have a mental framework for classifying any graph problem on sight, complete runnable solutions for the 10 most common interview problems, and the internal mechanics — why BFS gives shortest paths in unweighted graphs, why DFS finds cycles, why Union-Find beats DFS for dynamic connectivity — explained at the level an interviewer expects when they ask 'can you walk me through your reasoning?'

Breadth-First Search (BFS): The Shortest Path Pattern

Breadth-First Search is the definitive algorithm for finding the shortest path in an unweighted graph. It explores the graph in 'layers'—visiting all neighbors at distance 1, then distance 2, and so on. This guarantees that the first time you reach a target node, you've found the shortest route. In interviews, this pattern is frequently disguised as 'minimum number of moves to solve a puzzle' or 'nearest exit in a maze.'

io/thecodeforge/graphs/BfsNavigator.java · JAVA
1234567891011121314151617181920212223242526272829303132333435
package io.thecodeforge.graphs;

import java.util.*;

public class BfsNavigator {
    /**
     * io.thecodeforge implementation of Shortest Path in an Adjacency List
     * Time Complexity: O(V + E), Space Complexity: O(V)
     */
    public int findShortestPath(int nodes, List<List<Integer>> adj, int start, int target) {
        Queue<Integer> queue = new LinkedList<>();
        boolean[] visited = new boolean[nodes];
        int distance = 0;

        queue.add(start);
        visited[start] = true;

        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int current = queue.poll();
                if (current == target) return distance;

                for (int neighbor : adj.get(current)) {
                    if (!visited[neighbor]) {
                        visited[neighbor] = true;
                        queue.add(neighbor);
                    }
                }
            }
            distance++;
        }
        return -1; // No path found
    }
}
▶ Output
// Example: Input 0 -> 2, Distance: 2 moves.
🔥Forge Tip:
Type this code yourself rather than copy-pasting. The muscle memory of writing it will help it stick. Remember: For BFS, always use a Queue. For DFS, use a Stack (or recursion).

Topological Sort: Handling Task Dependencies

Topological sorting is only applicable to Directed Acyclic Graphs (DAGs). It provides a linear ordering of vertices such that for every directed edge $u \to v$, vertex $u$ comes before $v$. This is the foundation of build systems (like Gradle or Maven) and task scheduling. Kahn's Algorithm is the preferred iterative approach using in-degrees.

io/thecodeforge/graphs/KahnAlgorithm.java · JAVA
1234567891011121314151617181920212223242526272829303132333435363738
package io.thecodeforge.graphs;

import java.util.*;

public class DependencyResolver {
    /**
     * Resolves task order using Kahn's Algorithm (Topological Sort)
     */
    public int[] resolveOrder(int numTasks, int[][] dependencies) {
        int[] inDegree = new int[numTasks];
        List<List<Integer>> adj = new ArrayList<>();
        for (int i = 0; i < numTasks; i++) adj.add(new ArrayList<>());

        for (int[] dep : dependencies) {
            adj.get(dep[1]).add(dep[0]);
            inDegree[dep[0]]++;
        }

        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < numTasks; i++) {
            if (inDegree[i] == 0) queue.add(i);
        }

        int[] order = new int[numTasks];
        int index = 0;
        while (!queue.isEmpty()) {
            int curr = queue.poll();
            order[index++] = curr;

            for (int neighbor : adj.get(curr)) {
                inDegree[neighbor]--;
                if (inDegree[neighbor] == 0) queue.add(neighbor);
            }
        }

        return index == numTasks ? order : new int[0]; // Empty if cycle detected
    }
}
▶ Output
// Resolves build order: Task 0 -> Task 1 -> Task 2
💡Edge Case Alert:
Always check for cycles! If the final ordered list doesn't contain all nodes, the graph has a cycle, meaning a circular dependency exists.
AlgorithmCore PatternUse Case
BFSLevel-order traversalShortest path in unweighted graphs
DFSExhaustive recursionCycle detection, Pathfinding, Connected Components
DijkstraGreedy / Priority QueueShortest path in weighted (non-negative) graphs
Kahn's (Topo Sort)In-degree processingDependency resolution and scheduling
Union-FindDisjoint SetsDynamic connectivity and redundant edge detection

🎯 Key Takeaways

  • You now understand that graph problems are often just 'Matrix or Adjacency List' puzzles in disguise.
  • You've implemented BFS for shortest paths and Kahn's Algorithm for topological sorting using io.thecodeforge standards.
  • The secret to graph interviews is choosing the right data structure (Queue vs. Stack vs. Priority Queue) for the traversal pattern.
  • Practice daily — the forge only works when it's hot 🔥

⚠ Common Mistakes to Avoid

    Using DFS for shortest paths in unweighted graphs; DFS can find a path, but it's rarely the shortest.
    Forgetting to mark nodes as 'visited'—this is the #1 cause of Infinite Loops in graph problems.
    Not handling disconnected components; many problems require you to loop through all nodes to ensure you've explored separate islands of data.

Frequently Asked Questions

When should I use BFS over DFS in a graph interview?

Use BFS when you need the shortest path in an unweighted graph or need to explore nodes in layers (closest first). Use DFS when you need to explore every possible path, detect cycles, or perform a topological sort via recursion.

What is the best way to represent a graph: Adjacency Matrix or Adjacency List?

Adjacency Lists are usually preferred ($O(V+E)$ space) because most interview graphs are 'sparse.' Adjacency Matrices ($O(V^2)$ space) are only efficient for very 'dense' graphs where nearly every node is connected to every other node.

Can Dijkstra's algorithm handle negative weights?

No. Dijkstra's algorithm uses a greedy approach that assumes adding an edge never decreases the total path cost. For graphs with negative weights, you must use the Bellman-Ford algorithm.

🔥
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

← PreviousTop 10 DP Interview ProblemsNext →Top 10 Linked List Problems
Forged with 🔥 at TheCodeForge.io — Where Developers Are Forged