Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
Do we need on the node or the keys in the graph?
Are the BFS and DFS solutions same here?
{0,...,n-1}
. In each iteration, we can either DFS or BFS to remove all connected component nodes. The times that node is still in our graph when we iterate it is the number of connected components. HAPPY CASE
Input: n = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2
Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 1
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For graph problems, some things we want to consider are:
n-1
. We have the edge map, representing edges. For every non-visited node, we add it to the BFS queue. We run the BFS. If there's remaining nodes, we add it to the BFS queue again incrementing the count, since this is an unconnected component. We repeat until all nodes are visited. The runtime is O(E+V) where V = number of nodes and V = number of edges in the entire graph (all connected components) because you only drill down on a node (and all its neighbors) if you haven't seen it before.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Run a DFS, starting from a particular vertex, it will continue to visit the vertices depth-wise until there are no more adjacent vertices left to visit.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
class Solution {
ArrayList<ArrayList<Integer>> adj = new ArrayList();
public int countComponents(int n, int[][] edges) {
boolean [] visited = new boolean[n];
for(int i = 0; i < n; i++){
adj.add(new ArrayList());
}
for(int [] edge:edges){
int u =edge[0];
int v = edge[1];
adj.get(u).add(v);
adj.get(v).add(u);
}
int count=0;
for(int i = 0;i < n;i++){
if(visited[i] == false) {
// apply dfs
dfs(adj, visited, i);
count++;
}
}
return count;
}
// use dfs to traverse the graph to see if all the nodes can be covered
private void dfs(ArrayList<ArrayList<Integer>> adj, boolean[] visited, int s){
visited[s]=true;
for(int v:adj.get(s)){
if(visited[v]==false){
dfs(adj,visited,v);
}
}
}
}
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
# create adjacency list
adj_list = [[] for _ in range(n)]
for n1, n2 in edges:
adj_list[n1].append(n2)
adj_list[n2].append(n1)
count = 0
# keep track of visited nodes in set
seen = set()
queue = collections.deque()
for i in range(n):
if i not in seen:
queue.append(i)
seen.add(i)
count += 1
self.bfs(adj_list, queue, seen)
return count
# apply bfs
def bfs(self, adj_list, queue, seen):
while queue:
node = queue.popleft()
for neighbour in adj_list[node]:
if neighbour not in seen:
seen.add(neighbour)
queue.append(neighbour)
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Time Complexity: O(E + V)
, where E
= Number of edges, V
= Number of vertices
Space Complexity: O(E + V)
, where E
= Number of edges, V
= Number of vertices