Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if a graph has cycles.
DSA Python
def has_cycle(graph): visited = set() def dfs(node, parent): visited.add(node) for neighbor in graph[node]: if neighbor not in visited: if dfs(neighbor, node): return True elif neighbor != [1]: return True return False for node in graph: if node not in visited: if dfs(node, None): return True return False
Attempts:
3 left
💡 Hint
Common Mistakes
Using the current node instead of the parent node in the cycle check.
Not checking if the neighbor is different from the parent.
✗ Incorrect
The cycle check returns True if a neighbor is visited and is not the parent node, indicating a cycle.
2fill in blank
mediumComplete the code to add an edge in an undirected graph represented as adjacency list.
DSA Python
def add_edge(graph, u, v): graph.setdefault(u, []).append([1]) graph.setdefault(v, []).append(u)
Attempts:
3 left
💡 Hint
Common Mistakes
Appending u to u's own adjacency list.
Appending the whole graph instead of the node.
✗ Incorrect
To add an edge from u to v, append v to u's adjacency list.
3fill in blank
hardFix the error in the code that checks if a tree is a valid tree (connected and no cycles).
DSA Python
def valid_tree(n, edges): graph = {i: [] for i in range(n)} for u, v in edges: graph[u].append(v) graph[v].append(u) visited = set() def dfs(node, parent): visited.add(node) for neighbor in graph[node]: if neighbor not in visited: if dfs(neighbor, node): return True elif neighbor == [1]: return True return False if dfs(0, -1): return False return len(visited) == n
Attempts:
3 left
💡 Hint
Common Mistakes
Checking if neighbor == node instead of neighbor != parent.
Not handling the parent node correctly.
✗ Incorrect
The cycle check should return True if a neighbor is visited and is not the parent node, so the condition must check if neighbor != parent. Here, the error is that it checks neighbor == node, which is wrong.
4fill in blank
hardFill both blanks to create a dictionary comprehension that maps each node to its degree (number of edges).
DSA Python
degrees = {node: [1] for node in graph if len(graph[node]) [2] 0}Attempts:
3 left
💡 Hint
Common Mistakes
Using the adjacency list itself instead of its length.
Using >= instead of > which includes nodes with zero degree.
✗ Incorrect
The degree of a node is the length of its adjacency list. We want nodes with degree greater than 0.
5fill in blank
hardFill all three blanks to create a set comprehension that collects all leaf nodes (nodes with degree 1).
DSA Python
leaves = {node for node in graph if len(graph[node]) [1] 1 and node not in [2] and node != [3]Attempts:
3 left
💡 Hint
Common Mistakes
Using != instead of == for degree check.
Not excluding visited or parent nodes.
✗ Incorrect
Leaves have degree exactly 1. We exclude nodes already visited and the parent node.
