Peek Top Element of Stack in DSA Go - Time & Space Complexity
We want to understand how long it takes to look at the top item of a stack.
The question is: How does the time to peek change as the stack grows?
Analyze the time complexity of the following code snippet.
// Peek returns the top element of the stack without removing it
func (s *Stack) Peek() (int, bool) {
if len(s.items) == 0 {
return 0, false // stack is empty
}
return s.items[len(s.items)-1], true
}
This code checks if the stack is empty and then returns the last item added.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing the last element of the array (slice) directly.
- How many times: Exactly once per peek call, no loops or recursion.
Looking at the top element takes the same amount of time no matter how big the stack is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The operation count stays constant as the stack grows.
Time Complexity: O(1)
This means peeking the top element takes the same short time no matter how many items are in the stack.
[X] Wrong: "Peeking takes longer if the stack is bigger because it has to look through all items."
[OK] Correct: Peeking only looks at the last item directly, no need to check other items.
Knowing that peek is a quick, constant-time operation helps you explain stack behavior clearly in interviews.
"What if the stack was implemented as a linked list instead of an array? How would the time complexity of peek change?"
Practice
peek operation do in a stack?Solution
Step 1: Understand stack operations
A stack stores elements in a last-in, first-out order. Common operations include push (add), pop (remove), and peek (view top).Step 2: Define peek operation
Peek returns the top element without removing it, allowing you to see the current top without changing the stack.Final Answer:
Returns the top element without removing it -> Option AQuick Check:
Peek = View top element without removal [OK]
- Confusing peek with pop operation
- Thinking peek adds elements
- Assuming peek checks emptiness
stack?Solution
Step 1: Understand Go slice indexing
Go slices are zero-indexed. The last element is at index length-1.Step 2: Identify correct top element access
To peek top, access stack[len(stack)-1]. Using len(stack) is out of range, 0 is bottom, and negative index is invalid.Final Answer:
top := stack[len(stack)-1] -> Option AQuick Check:
Last element index = length-1 [OK]
- Using len(stack) as index (out of range)
- Using negative index (not supported in Go)
- Accessing stack[0] which is bottom
stack := []int{10, 20, 30}
top := stack[len(stack)-1]
fmt.Println(top)Solution
Step 1: Analyze stack contents
The stack slice contains elements [10, 20, 30], where 30 is the last element (top).Step 2: Evaluate peek operation
top := stack[len(stack)-1] accesses stack[2], which is 30, then prints it.Final Answer:
30 -> Option DQuick Check:
Top element = 30 [OK]
- Printing bottom element instead of top
- Indexing out of range causing error
- Confusing output with pop operation
stack := []int{}
top := stack[len(stack)-1]
fmt.Println(top)Solution
Step 1: Check stack initialization
The stack is initialized as an empty slice with length 0.Step 2: Analyze peek operation
Accessing stack[len(stack)-1] means stack[-1], which is invalid and causes runtime panic: index out of range.Final Answer:
Index out of range runtime error -> Option BQuick Check:
Empty slice peek causes runtime error [OK]
- Assuming peek returns zero on empty stack
- Ignoring runtime panic possibility
- Confusing syntax error with runtime error
stack := []int{5, 10, 15}, write the correct Go code snippet to safely peek the top element and handle the case when the stack is empty.Solution
Step 1: Check stack length before peeking
To avoid runtime error, verify stack length > 0 before accessing top element.Step 2: Access top element safely and handle empty case
If stack is not empty, peek top with stack[len(stack)-1]. Otherwise, print "Stack is empty" message.Final Answer:
if len(stack) > 0 { top := stack[len(stack)-1] fmt.Println(top) } else { fmt.Println("Stack is empty") } -> Option CQuick Check:
Check length before peek to avoid errors [OK]
- Not checking length before peek
- Using len(stack) as index
- Assuming nil check is enough
Ready to prove it?
Pass the test and this pattern moves unknown
