Bird
Raised Fist0
DSA Goprogramming~10 mins

Peek Top Element of Stack in DSA Go - Execution Trace

Choose your learning style10 modes available
Concept Flow - Peek Top Element of Stack
Start
↓
Check if stack is empty?
Yes→Return error or nil
No↓
Access top element
↓
Return top element
↓
End
The flow checks if the stack is empty, if not, it accesses and returns the top element without removing it.
Execution Sample
DSA Go
package main

import "fmt"

func main() {
    stack := []int{10, 20, 30}
    top := stack[len(stack)-1]
    fmt.Println(top)
}
This code gets the top element of a stack represented by a slice and prints it.
Execution Table
StepOperationStack StatePointer ChangesVisual State
1Start with stack initialized[10, 20, 30]top pointer not set10 -> 20 -> 30 -> null
2Check if stack is empty[10, 20, 30]No change10 -> 20 -> 30 -> null
3Access top element at index len(stack)-1[10, 20, 30]top = 3010 -> 20 -> 30 -> null (top points here)
4Return top element[10, 20, 30]No change10 -> 20 -> 30 -> null (top points here)
5End[10, 20, 30]No change10 -> 20 -> 30 -> null (top points here)
💡 Stack is not empty, top element accessed and returned without removal.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
stack[10, 20, 30][10, 20, 30][10, 20, 30][10, 20, 30]
topundefinedundefined3030
Key Moments - 3 Insights
Why do we check if the stack is empty before peeking?
Because if the stack is empty, there is no top element to return. The execution_table row 2 shows the check to avoid errors.
Does peeking remove the top element from the stack?
No, peeking only reads the top element without removing it. The stack state remains the same in all steps as shown in the execution_table.
How do we find the top element in a stack implemented as a slice?
We access the element at index len(stack)-1, as shown in execution_table step 3 where top = stack[len(stack)-1].
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'top' after step 3?
A20
B30
C10
Dundefined
💡 Hint
Check the 'Pointer Changes' column in step 3 where top is assigned.
At which step does the code check if the stack is empty?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Operation' column for the empty check.
If the stack was empty, what would happen according to the concept flow?
AReturn error or nil
BAdd a new element
CReturn the last element
DRemove the top element
💡 Hint
Refer to the concept_flow where empty stack leads to returning error or nil.
Concept Snapshot
Peek Top Element of Stack:
- Check if stack is empty
- If empty, return error or nil
- Else, access element at index len(stack)-1
- Return this element without removing
- Stack remains unchanged
Full Transcript
To peek the top element of a stack, first check if the stack is empty to avoid errors. If it is not empty, access the last element in the stack, which is at index length minus one. This element is the top of the stack. Return this element without removing it, so the stack stays the same. This process ensures safe access to the top element without modifying the stack.

Practice

(1/5)
1. What does the peek operation do in a stack?
easy
A. Returns the top element without removing it
B. Removes the top element from the stack
C. Adds a new element to the top of the stack
D. Checks if the stack is empty

Solution

  1. 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).
  2. Step 2: Define peek operation

    Peek returns the top element without removing it, allowing you to see the current top without changing the stack.
  3. Final Answer:

    Returns the top element without removing it -> Option A
  4. Quick Check:

    Peek = View top element without removal [OK]
Hint: Peek shows top without removing it [OK]
Common Mistakes:
  • Confusing peek with pop operation
  • Thinking peek adds elements
  • Assuming peek checks emptiness
2. Which of the following is the correct Go syntax to peek the top element of a stack implemented as a slice named stack?
easy
A. top := stack[len(stack)-1]
B. top := stack[-1]
C. top := stack[0]
D. top := stack[len(stack)]

Solution

  1. Step 1: Understand Go slice indexing

    Go slices are zero-indexed. The last element is at index length-1.
  2. 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.
  3. Final Answer:

    top := stack[len(stack)-1] -> Option A
  4. Quick Check:

    Last element index = length-1 [OK]
Hint: Use len(stack)-1 to get top index [OK]
Common Mistakes:
  • Using len(stack) as index (out of range)
  • Using negative index (not supported in Go)
  • Accessing stack[0] which is bottom
3. What will be the output of the following Go code snippet?
stack := []int{10, 20, 30}
top := stack[len(stack)-1]
fmt.Println(top)
medium
A. 10
B. Runtime error
C. 20
D. 30

Solution

  1. Step 1: Analyze stack contents

    The stack slice contains elements [10, 20, 30], where 30 is the last element (top).
  2. Step 2: Evaluate peek operation

    top := stack[len(stack)-1] accesses stack[2], which is 30, then prints it.
  3. Final Answer:

    30 -> Option D
  4. Quick Check:

    Top element = 30 [OK]
Hint: Last element is top, printed value is 30 [OK]
Common Mistakes:
  • Printing bottom element instead of top
  • Indexing out of range causing error
  • Confusing output with pop operation
4. Identify the error in the following Go code that tries to peek the top element of a stack:
stack := []int{}
top := stack[len(stack)-1]
fmt.Println(top)
medium
A. Syntax error due to missing import
B. Index out of range runtime error
C. top will be zero by default
D. Code runs fine and prints 0

Solution

  1. Step 1: Check stack initialization

    The stack is initialized as an empty slice with length 0.
  2. Step 2: Analyze peek operation

    Accessing stack[len(stack)-1] means stack[-1], which is invalid and causes runtime panic: index out of range.
  3. Final Answer:

    Index out of range runtime error -> Option B
  4. Quick Check:

    Empty slice peek causes runtime error [OK]
Hint: Empty stack peek causes index error [OK]
Common Mistakes:
  • Assuming peek returns zero on empty stack
  • Ignoring runtime panic possibility
  • Confusing syntax error with runtime error
5. Given a stack implemented as a slice 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.
hard
A. top := stack[0] fmt.Println(top)
B. top := stack[len(stack)] fmt.Println(top)
C. if len(stack) > 0 { top := stack[len(stack)-1] fmt.Println(top) } else { fmt.Println("Stack is empty") }
D. if stack != nil { top := stack[len(stack)-1] fmt.Println(top) }

Solution

  1. Step 1: Check stack length before peeking

    To avoid runtime error, verify stack length > 0 before accessing top element.
  2. 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.
  3. Final Answer:

    if len(stack) > 0 { top := stack[len(stack)-1] fmt.Println(top) } else { fmt.Println("Stack is empty") } -> Option C
  4. Quick Check:

    Check length before peek to avoid errors [OK]
Hint: Check length > 0 before peek [OK]
Common Mistakes:
  • Not checking length before peek
  • Using len(stack) as index
  • Assuming nil check is enough
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard