Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Graph itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)A graph models arbitrary relationships, including cycles and converging paths. Define vertices, direction and duplicate policy before storage, then mark discovery once so traversal counts reachable nodes rather than repeated paths.
9 practice exercises14 interview problems
Recognize it when Entities connect through arbitrary edges rather than one-parent hierarchy.
Checking your account…
A graph separates entities (vertices) from relationships (edges). Unlike a tree, a vertex may have multiple incoming paths, and cycles may return to already discovered state. Direction, weight, parallel edges, and self-loops are contract decisions, not implementation details.
For an undirected edge, record both directions; for a directed edge, record only source to target. Degree, reachability, and cycle meaning change with direction. Normalize duplicate-edge policy before building storage so traversal and complexity claims match the logical graph.
An adjacency list uses O(V + E) space and enumerates actual neighbors efficiently. An adjacency matrix uses O(V squared) space but tests a particular edge in O(1). Compare density and query type rather than choosing by habit. Sets deduplicate neighbors; lists preserve repeated edges and input order.
def build_graph_representations(node_count, edges):
adjacency = [set() for _ in range(node_count)]
matrix = [[0 for _ in range(node_count)] for _ in range(node_count)]
for left, right in edges:
adjacency[left].add(right)
adjacency[right].add(left)
matrix[left][right] = 1
matrix[right][left] = 1
return [[sorted(neighbors) for neighbors in adjacency], matrix]Implement build_graph_representations(node_count, edges). Deduplicate undirected edges and return sorted adjacency lists plus an adjacency matrix. node_count is a nonnegative integer; every edge endpoint satisfies 0 <= endpoint < node_count.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def build_graph_representations(node_count, edges):
adjacency = [set() for _ in range(node_count)]
matrix = [[0 for _ in range(node_count)] for _ in range(node_count)]
for left, right in edges:
adjacency[left].add(right)
adjacency[right].add(left)
matrix[left][right] = 1
matrix[right][left] = 1
return [[sorted(neighbors) for neighbors in adjacency], matrix]DFS and BFS need visited state because a graph can contain cycles and converging paths. Mark when an item is discovered to prevent duplicate frontier entries. To find components, begin a traversal from each still-unvisited vertex; one traversal consumes exactly one connected component.
def component_sizes(node_count, edges):
adjacency = [[] for _ in range(node_count)]
for left, right in edges:
adjacency[left].append(right)
adjacency[right].append(left)
visited = set()
sizes = []
for start in range(node_count):
if start in visited:
continue
visited.add(start)
stack = [start]
size = 0
while stack:
node = stack.pop()
size += 1
for neighbor in adjacency[node]:
if neighbor not in visited:
visited.add(neighbor)
stack.append(neighbor)
sizes.append(size)
return sizesImplement component_sizes(node_count, edges). Include isolated vertices and return undirected component sizes in increasing start-vertex order. node_count is a nonnegative integer; every edge endpoint satisfies 0 <= endpoint < node_count.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def component_sizes(node_count, edges):
adjacency = [[] for _ in range(node_count)]
for left, right in edges:
adjacency[left].append(right)
adjacency[right].append(left)
visited = set()
sizes = []
for start in range(node_count):
if start in visited:
continue
visited.add(start)
stack = [start]
size = 0
while stack:
node = stack.pop()
size += 1
for neighbor in adjacency[node]:
if neighbor not in visited:
visited.add(neighbor)
stack.append(neighbor)
sizes.append(size)
return sizesThe component Lab receives five declared vertices but only a three-node chain of edges. It must return two additional one-node components for vertices 3 and 4. Discovery is recorded before each push.
print(component_sizes(5, [(0, 1), (1, 2)])) followed by print(component_sizes(0, []))
| Step | Executed statement | State | Why |
|---|---|---|---|
| 1 | adjacency[left].append(right); adjacency[right].append(left) |
after build loop: adjacency = [[1], [0, 2], [1], [], []] |
All five slots exist, including isolated vertices. |
| 2 | visited.add(start); stack = [start]; size = 0 |
start = 0; visited = {0}; stack = [0] |
The first component begins with one discovered node. |
| 3 | node = stack.pop(); size += 1; visited.add(neighbor); stack.append(neighbor) |
after node 0: size = 1; visited = {0, 1}; stack = [1] |
Marking node 1 now prevents another path from rescheduling it. |
| 4 | node = stack.pop(); size += 1; visited.add(neighbor); stack.append(neighbor) |
after node 1: size = 2; visited = {0, 1, 2}; stack = [2] |
The parent 0 is skipped while new neighbor 2 enters once. |
| 5 | node = stack.pop(); size += 1; sizes.append(size) |
after node 2: sizes = [3]; starts 1 and 2 skipped |
The stack empties only after the complete region is processed. |
| 6 | visited.add(start); stack = [start]; size = 0; node = stack.pop(); size += 1; sizes.append(size) |
starts 3 and 4 each yield size 1; result = [3, 1, 1] |
An empty neighbor list still represents a valid one-node component. |
| Output | |
|---|---|
| 1 | [3, 1, 1] |
| 2 | [] |
The outer start loop determines component order and preserves isolated vertices. Within a component, visited prevents revisiting an undirected parent or a converging route; the stack controls processing order rather than membership.
The deque reference(opens in a new tab) supports the BFS frontier; a list supports iterative DFS as a stack. Both traversals are O(V + E) with adjacency lists because each vertex and stored edge is examined a bounded number of times.
Choose a graph for arbitrary relationships, multiple paths, cycles, or dependencies. Choose an implicit grid when neighbors derive from coordinates instead of stored edges. Choose a rooted tree when every non-root node has one parent and there is a unique root path; then parent state can replace a general visited set. Compare BFS, DFS, topological order, and shortest-path algorithms only after the edge contract is known.
State V, E, direction, weight, and duplicate policy before coding. Define what visited means and when it changes. Give O(V + E) for adjacency-list traversal, noting that undirected edges are stored twice, and distinguish frontier space from representation space.
Build Graph Representations(opens in a new tab) forces a storage decision. Course Schedule(opens in a new tab) adds direction and cycle detection to model prerequisites.
Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Graph itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Build both representations | O(V * V + E + sum(d * log(d + 1))) | O(V * V + E * V + sum(d * log(d + 1))) | d is each distinct neighbor count; sorting is charged per vertex. Average uses ordinary hashing; worst permits collision-heavy set insertion. |
| Measure components | O(V + E) | O((V + E) * V) | Includes adjacency, seen/frontier and output. Average uses ordinary integer hashing; collision-heavy seen operations can degrade it. |
O(V * V + E) for build both representations; O(V + E) for measure components.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
A one-way insertion loses the reverse reachability promised by an undirected graph.
Prevent it: Insert both endpoint directions under an undirected contract.
adjacency[left].append(right)adjacency[left].append(right)
adjacency[right].append(left)Where you will hit this: Build Graph Representations(opens in a new tab)
Repeated neighbors can add the same pending vertex twice before processing begins.
Prevent it: Mark each newly discovered neighbor before pushing it.
for neighbor in neighbors:
if neighbor not in seen:
frontier.append(neighbor)for neighbor in neighbors:
if neighbor not in seen:
seen.add(neighbor)
frontier.append(neighbor)Where you will hit this: Build Graph Representations(opens in a new tab)
Isolated vertices never appear in edges and disappear from the model if endpoints define the universe.
Prevent it: Use the declared node count to initialize every vertex.
vertices = {node for edge in edges for node in edge}vertices = set(range(node_count))Where you will hit this: Course Schedule(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-12