Understanding Key Graph Traversal Questions for Meta Interviews
Written on
Meta, formerly known as Facebook, is recognized for its stringent software engineering interview procedures. Among the technical questions often posed, graph traversal queries are prevalent. Mastering graph algorithms is vital as they facilitate efficient data management and offer foundational insights into intricate systems. This article highlights seven critical graph traversal questions commonly encountered in Meta's software engineering interviews, supplemented with Python solutions for each.
> Consider ByteByteGo’s renowned System Design Interview Course for your next interview!
Depth-First Search (DFS)
Question:
Implement the Depth-First Search algorithm on a graph represented as an adjacency list.
def dfs(graph, node, visited):
if node not in visited:
print(node)
visited.add(node)
for neighbour in graph[node]:
dfs(graph, neighbour)
# Test the function
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
visited = set()
dfs(graph, 'A', visited)
dfs(graph, 'A', visited)
Breadth-First Search (BFS)
Question:
Implement the Breadth-First Search algorithm on a graph presented as an adjacency list.
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
vertex = queue.popleft()
if vertex not in visited:
print(vertex)
visited.add(vertex)
queue.extend(graph[vertex])
# Test the function
bfs(graph, 'A')
> Don’t forget to secure your copy of Designing Data Intensive Applications, a crucial read for system design interview preparation!
Cycle Detection in a Directed Graph
Question:
Create a function to identify a cycle in a directed graph.
def has_cycle(graph, node, visited, stack):
visited.add(node)
stack.add(node)
for neighbour in graph[node]:
if neighbour not in visited:
if has_cycle(graph, neighbour, visited, stack):
return True
elif neighbour in stack:
return True
stack.remove(node)
return False
# Test the function
visited = set()
stack = set()
print(has_cycle(graph, 'A', visited, stack))
> Gain an advantage over your peers with the Grokking the Advanced System Design Interview course to secure that dream position! Avoid wasting hours on Leetcode; learn strategies with the course Grokking the Coding Interview: Patterns for Coding Questions.
Counting Connected Components
Question:
Determine the number of connected components in an undirected graph.
def dfs(graph, node, visited):
visited.add(node)
for neighbour in graph[node]:
if neighbour not in visited:
dfs(graph, neighbour)
def count_components(graph):
visited = set()
count = 0
for node in graph:
if node not in visited:
dfs(graph, node, visited)
count += 1
return count
Topological Sort
Question:
Execute Topological Sort on a directed graph.
from collections import deque
def topological_sort(graph):
indegree = {node: 0 for node in graph}
for node in graph:
for neighbour in graph[node]:
indegree[neighbour] += 1
queue = deque([node for node in indegree if indegree[node] == 0])
result = []
while queue:
current = queue.popleft()
result.append(current)
for neighbour in graph[current]:
indegree[neighbour] -= 1
if indegree[neighbour] == 0:
queue.append(neighbour)
return result
> Enhance your earnings with Grokking Comp Negotiation in Tech.
Dijkstra’s Shortest Path Algorithm
Question:
Implement Dijkstra’s algorithm to discover the shortest path in a weighted graph.
import heapq
def dijkstra(graph, start):
distances = {node: float('infinity') for node in graph}
distances[start] = 0
priority_queue = [(0, start)]
while priority_queue:
current_distance, current_vertex = heapq.heappop(priority_queue)
if current_distance > distances[current_vertex]:
continue
for neighbour, weight in graph[current_vertex].items():
distance = current_distance + weight
if distance < distances[neighbour]:
distances[neighbour] = distance
heapq.heappush(priority_queue, (distance, neighbour))
return distances
Longest Path in a DAG
Question:
Write a function to ascertain the longest path in a Directed Acyclic Graph (DAG).
def longest_path(graph):
stack = []
visited = set()
def dfs(node):
visited.add(node)
for neighbour in graph[node]:
if neighbour not in visited:
dfs(neighbour)
stack.append(node)
for node in graph:
if node not in visited:
dfs(node)
dist = {node: float('-infinity') for node in graph}
while stack:
current = stack.pop()
if dist[current] == float('-infinity'):
dist[current] = 0
for neighbour in graph[current]:
dist[neighbour] = max(dist[neighbour], dist[current] + 1)
return max(dist.values())
Prepare thoroughly, practice these problems, and you'll excel in your Meta software engineering interviews!
If this article proved beneficial, remember to share it with future software engineers and follow us for more insightful content. Wishing you the best on your path to becoming a Meta engineer!