Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the in-degree slice for all vertices.
DSA Go
inDegree := make([]int, [1])Attempts:
3 left
💡 Hint
Common Mistakes
Using capacity instead of length for the slice size.
Initializing with 0 or 1 which is too small.
✗ Incorrect
The in-degree slice must have the same length as the number of vertices in the graph, which is len(graph).
2fill in blank
mediumComplete the code to enqueue vertices with zero in-degree.
DSA Go
for i := 0; i < len(inDegree); i++ { if inDegree[i] [1] 0 { queue = append(queue, i) } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' or '<' instead of '==' causing wrong vertices to be enqueued.
Using '!=' which includes all non-zero in-degree vertices.
✗ Incorrect
Vertices with in-degree equal to zero are the starting points for topological sorting.
3fill in blank
hardFix the error in the code that decreases the in-degree of adjacent vertices.
DSA Go
for _, neighbor := range graph[node] { inDegree[neighbor] [1] if inDegree[neighbor] == 0 { queue = append(queue, neighbor) } }
Attempts:
3 left
💡 Hint
Common Mistakes
Increasing in-degree instead of decreasing it.
Assigning in-degree to 1 incorrectly.
Multiplying in-degree by 1 which does nothing.
✗ Incorrect
We decrease the in-degree of neighbors by 1 when we remove an edge from the graph.
4fill in blank
hardFill both blanks to complete the BFS loop that processes the queue.
DSA Go
for len(queue) > 0 { node := queue[1] queue = queue[2] // process node }
Attempts:
3 left
💡 Hint
Common Mistakes
Using [:1] which returns a slice, not the element.
Using [-1:] which is invalid in Go.
Removing the wrong part of the queue.
✗ Incorrect
We get the first element with queue[0] and remove it by slicing queue[1:].
5fill in blank
hardFill all three blanks to complete the function that returns the topological order or an empty slice if a cycle exists.
DSA Go
func topologicalSort(graph [][]int) []int {
inDegree := make([]int, [1])
for _, edges := range graph {
for _, v := range edges {
inDegree[v] [2]
}
}
queue := []int{}
for i := 0; i < len(inDegree); i++ {
if inDegree[i] == 0 {
queue = append(queue, i)
}
}
var order []int
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
order = append(order, node)
for _, neighbor := range graph[node] {
inDegree[neighbor] [3]
if inDegree[neighbor] == 0 {
queue = append(queue, neighbor)
}
}
}
if len(order) != len(graph) {
return []int{}
}
return order
}Attempts:
3 left
💡 Hint
Common Mistakes
Using cap(graph) instead of len(graph).
Decrementing in-degree when counting edges instead of incrementing.
Incrementing in-degree when removing edges instead of decrementing.
✗ Incorrect
We initialize inDegree with len(graph), increment inDegree[v] for each edge, and decrement inDegree[neighbor] when processing.
