Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare an adjacency list for a graph with 5 vertices.
DSA Java
List<List<Integer>> adjList = new ArrayList<>(); for (int i = 0; i < [1]; i++) { adjList.add(new ArrayList<>()); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong number of vertices in the loop.
Not initializing the inner lists.
✗ Incorrect
The graph has 5 vertices, so we create 5 empty lists inside the adjacency list.
2fill in blank
mediumComplete the code to add an edge from vertex 2 to vertex 4 in the adjacency list.
DSA Java
adjList.get([1]).add(4);
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong index for the vertex.
Adding the edge to the wrong list.
✗ Incorrect
To add an edge from vertex 2, we get the list at index 2 and add 4 to it.
3fill in blank
hardFix the error in the code to correctly add an undirected edge between vertices 1 and 3.
DSA Java
adjList.get(1).add([1]); adjList.get(3).add(1);
Attempts:
3 left
💡 Hint
Common Mistakes
Adding the wrong vertex to the adjacency list.
Only adding one direction of the edge.
✗ Incorrect
To add an undirected edge between 1 and 3, add 3 to 1's list and 1 to 3's list.
4fill in blank
hardFill both blanks to print all neighbors of vertex 0 using a for-each loop.
DSA Java
for (Integer [1] : adjList.get(0)) { System.out.println([2]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable name in the print statement.
Confusing the adjacency list with the neighbor variable.
✗ Incorrect
Use 'neighbor' as the loop variable and print it to show all neighbors of vertex 0.
5fill in blank
hardFill all three blanks to create an adjacency list from edges and print neighbors of vertex 1.
DSA Java
int[][] edges = [1]; List<List<Integer>> adjList = new ArrayList<>(); for (int i = 0; i < 3; i++) { adjList.add(new ArrayList<>()); } for (int[] edge : edges) { adjList.get(edge[0]).add(edge[1]); adjList.get(edge[1]).add(edge[0]); } for (Integer [2] : adjList.get([3])) { System.out.print([2] + " "); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect edge arrays.
Using wrong loop variable names.
Printing neighbors of the wrong vertex.
✗ Incorrect
Use edges {{0,1}, {1,2}, {2,0}}; loop variable 'neighbor'; print neighbors of vertex 1.
