You have a list of tasks to process. You want to process the oldest task first, then the next oldest, and so on.
Which data structure should you use?
Think about which data structure follows First-In-First-Out (FIFO) order.
A queue processes elements in the order they arrive, which is First-In-First-Out (FIFO). This means the oldest task is processed first. A stack processes elements Last-In-First-Out (LIFO), so it would process the newest task first.
Consider the following Go code snippets for stack and queue operations. What is the printed output after all operations?
package main import "fmt" func main() { stack := []int{} queue := []int{} // Stack operations stack = append(stack, 1) stack = append(stack, 2) stack = append(stack, 3) top := stack[len(stack)-1] stack = stack[:len(stack)-1] // Queue operations queue = append(queue, 1) queue = append(queue, 2) queue = append(queue, 3) front := queue[0] queue = queue[1:] fmt.Printf("Stack top: %d, Remaining stack: %v\n", top, stack) fmt.Printf("Queue front: %d, Remaining queue: %v\n", front, queue) }
Remember that stack removes from the end and queue removes from the front.
The stack removes the last added element (3), leaving [1 2]. The queue removes the first added element (1), leaving [2 3].
What error will this Go code produce when trying to pop from an empty stack?
package main import "fmt" func main() { stack := []int{} // Pop operation top := stack[len(stack)-1] stack = stack[:len(stack)-1] fmt.Println(top) }
What happens if you try to access an element in an empty slice?
Accessing stack[len(stack)-1] when stack is empty causes an index out of range runtime error.
You are designing an undo feature for a text editor. Each action is saved and the most recent action should be undone first.
Which data structure is best suited for this?
Undo means reversing the last action done.
A stack follows Last-In-First-Out (LIFO), so the most recent action is undone first, which fits the undo feature.
In which scenario is a queue preferred over a stack?
Choose the best answer.
Think about BFS and DFS algorithms and their data structures.
Breadth-first search (BFS) uses a queue to explore nodes level by level. Depth-first search (DFS) uses a stack or recursion to explore nodes deeply.
