The peek operation is one of the basic operations performed on a stack in Data Structures and Algorithms (DSA). It is used to access the top element of a stack without removing it. A stack follows the Last In, First Out (LIFO) principle, which means the last element inserted is the first one to be removed. The peek operation helps retrieve the most recently inserted element while keeping the stack unchanged.
Table of Contents
1. What Is the Peek Operation in a Stack?
The peek operation is used to view or access the top element of a stack without removing it.
Since a stack follows the LIFO principle, the top element is always the most recently inserted element.
In JavaScript, when an array is used as a stack, the top element can be accessed using the array's length property.
Example:
// Access the top element of a stack without removing it. let stack = [10, 20, 30]; let topElement = stack[stack.length - 1]; console.log(topElement); console.log(stack);
Output:
30
[10, 20, 30]
In this example, the peek operation returns 30 because it is the last element in the stack. The original stack remains unchanged.
2. How Does the Peek Operation Work?
The peek operation follows a simple process to access the top element.
- Start with an existing stack.
- Check whether the stack is empty.
- If the stack is empty, display an appropriate message.
- If the stack contains elements, access the top element.
- Return the top element without removing it.
This operation allows programmers to retrieve the top value without modifying the stack.
3. Algorithm for Peek Operation
An algorithm describes the logical steps required to perform the peek operation.
Algorithm:
- Start.
- Check whether the stack is empty.
- If the stack is empty, display "Stack is Empty".
- Otherwise, access the element at the top position.
- Return the top element.
- Stop.
Pseudocode:
PEEK(STACK, TOP)
1. If TOP = -1
Print "Stack is Empty"
Return
2. ITEM = STACK[TOP]
3. Return ITEM
This algorithm first checks whether the stack contains any elements. If it is not empty, it returns the element at the top without changing the stack.
4. Peek Operation Using JavaScript Arrays
JavaScript provides a simple way to perform the peek operation using array indexing.
When an array is used as a stack, the last element represents the top. The expression stack[stack.length - 1] accesses that element.
Example:
// Perform the peek operation using a JavaScript array.
let stack = [10, 20, 30, 40];
let topElement = stack[stack.length - 1];
console.log("Top element:", topElement);
console.log("Stack:", stack);
Output:
Top element: 40
Stack: [10, 20, 30, 40]
In this example, the peek operation returns 40, which is the last element of the array. No element is removed, so the stack remains unchanged.
5. Peek Operation Using a Stack Class
A stack can be implemented using a JavaScript class to organize its operations. The peek method can be defined inside the class to access the top element safely.
Example:
// Implement the peek operation using a JavaScript stack class.
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
peek() {
if (this.items.length === 0) {
return "Stack is Empty";
}
return this.items[this.items.length - 1];
}
}
let stack = new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
console.log(stack.peek());
console.log(stack.peek());
Output:
30
30
In this implementation, the peek() method returns the last element of the stack. It does not modify the array, so calling the method multiple times returns the same value as long as no other operation changes the stack.
6. Peek Operation on an Empty Stack
An empty stack does not contain any elements. Therefore, the peek operation cannot return a valid stack element.
Before accessing the top element, it is important to check whether the stack is empty. This prevents attempts to access an invalid position.
Example:
// Handle the peek operation when a stack is empty.
let stack = [];
function peek() {
if (stack.length === 0) {
return "Stack is Empty";
}
return stack[stack.length - 1];
}
console.log(peek());
stack.push(50);
console.log(peek());
Output:
Stack is Empty
50
In this example, the first peek operation returns a message because the stack is empty. After inserting 50, the peek operation successfully returns the top element.
7. Difference Between Peek and Pop
Peek and pop are two important stack operations. Both access the top element, but they behave differently.
| Feature | Peek | Pop |
|---|---|---|
| Purpose | Accesses the top element | Removes the top element |
| Stack modification | Does not modify the stack | Modifies the stack |
| Returns | Top element | Removed element |
| Element removal | No | Yes |
| Time complexity | O(1) | O(1) |
Example:
// Compare peek and pop operations on a stack.
let stack = [10, 20, 30]
console.log("Peek:", stack[stack.length - 1]);
console.log("After Peek:", stack);
console.log("Pop:", stack.pop());
console.log("After Pop:", stack);
Output:
Peek: 30
After Peek: [10, 20, 30]
Pop: 30
After Pop: [10, 20]
In this example, peek accesses 30 without removing it. The pop operation then removes 30 from the stack.
8. Time Complexity of Peek Operation
Time complexity describes how the execution time of an operation changes as the number of elements increases.
| Operation | Time Complexity | Description |
|---|---|---|
| Peek | O(1) | Accesses the top element directly. |
The peek operation takes constant time, O(1), because it accesses the top element directly without searching through the stack.
9. Applications of Peek Operation
The peek operation is useful in several programming concepts and real-world applications.
- Expression Evaluation: Peek helps access the top operator or operand while evaluating mathematical expressions.
- Function Calls: It can be used to inspect the most recent function call information stored on a call stack.
- Undo Operations: Applications can inspect the most recent action before performing an undo operation.
- Backtracking: Algorithms can check the current state stored at the top of a stack before deciding the next step.
- Depth-First Search: Peek can inspect the current node at the top of the stack without removing it.
- Parentheses Matching: Peek helps check the most recently stored opening bracket when processing closing brackets.
10. Common Mistakes to Avoid
- Confusing Peek with Pop: Peek accesses the top element, while pop removes it.
- Ignoring Empty Stack Conditions: Always check whether the stack is empty before accessing its top element.
- Using the Wrong Index: In an array-based stack, use stack.length - 1 to access the top element.
- Modifying the Stack During Peek: The peek operation should not insert or remove any elements.
- Assuming Peek Works on an Empty Stack: An empty stack has no top element, so handle this condition properly.
11. Frequently Asked Questions
1. What is the peek operation in a stack?
The peek operation returns the top element of a stack without removing it.
2. Does peek modify the stack?
No. The peek operation only accesses the top element and leaves the stack unchanged.
3. How can peek be implemented in JavaScript?
The top element can be accessed using stack[stack.length - 1] when an array is used as a stack.
4. What happens when peek is performed on an empty stack?
There is no top element to access, so the program should handle the empty stack condition.
5. What is the time complexity of the peek operation?
The peek operation takes O(1) time because it accesses the top element directly.
Conclusion
The peek operation is an important stack operation used to access the top element without removing it. It follows the LIFO principle and takes constant time, O(1), to execute. In JavaScript, the top element can be accessed using array indexing or a custom stack class. Understanding the peek operation helps developers manage stack elements efficiently and build a strong foundation for learning other DSA concepts.
0 Comments