Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a graph using adjacency list representation.
DSA C#
Dictionary<int, List<int>> graph = new Dictionary<int, List<int>>(); graph.Add(1, new List<int> { [1] });
Attempts:
3 left
💡 Hint
Common Mistakes
Adding multiple nodes without commas inside the List constructor.
Using parentheses instead of braces for List initialization.
✗ Incorrect
The adjacency list for node 1 should contain its connected nodes. Here, node 1 connects to node 2 only.
2fill in blank
mediumComplete the code to add an edge between two nodes in an undirected graph.
DSA C#
void AddEdge(Dictionary<int, List<int>> graph, int u, int v) {
graph[u].Add([1]);
graph[v].Add(u);
}Attempts:
3 left
💡 Hint
Common Mistakes
Adding u to u's adjacency list instead of v.
Using incorrect variable names.
✗ Incorrect
To add an edge from u to v, we add v to u's adjacency list.
3fill in blank
hardFix the error in the code that tries to check if a graph contains a cycle.
DSA C#
bool HasCycle(int node, int parent, Dictionary<int, List<int>> graph, HashSet<int> visited) {
visited.Add(node);
foreach (var neighbor in graph[node]) {
if (!visited.Contains(neighbor)) {
if (HasCycle(neighbor, node, graph, visited)) return true;
} else if (neighbor != [1]) {
return true;
}
}
return false;
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing neighbor to node instead of parent.
Not checking for cycles properly.
✗ Incorrect
When checking for cycles, we ignore the edge back to the parent node to avoid false positives.
4fill in blank
hardFill both blanks to create a graph that models a social network where users can be friends with multiple users.
DSA C#
var socialGraph = new Dictionary<string, List<string>>(); socialGraph["Alice"] = new List<string> { [1] }; socialGraph["Bob"] = new List<string> { [2] };
Attempts:
3 left
💡 Hint
Common Mistakes
Using single names instead of lists.
Not matching friend names correctly.
✗ Incorrect
Alice is friends with Bob and Charlie; Bob is friends with Alice and David.
5fill in blank
hardFill all three blanks to create a graph that models a road network with weighted edges.
DSA C#
var roadGraph = new Dictionary<string, List<(string, int)>>(); roadGraph["CityA"] = new List<(string, int)> { ([1], [2]) }; roadGraph["CityB"] = new List<(string, int)> { ([3], 10) };
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing city names and weights in wrong order.
Using incorrect tuple syntax.
✗ Incorrect
CityA connects to CityB with weight 5; CityB connects back to CityA with weight 10.
