Implement a Stack
JavaScript
easy
10 mins
Implement a Stack data structure in JavaScript. A stack follows the Last-In-First-Out (LIFO) principle. Your implementation should include the following operations:
push(element): Add an element to the top of the stack and return sizepop(): Remove and return the top element from the stackpeek(): Return the top element without removing itisEmpty(): Check if the stack is emptysize(): Return the number of elements in the stackclear(): Remove all elements from the stack
Example Inputs & Outputs
const stack = new Stack(); stack.isEmpty(); // true stack.push(10); // 1 stack.push(20); // 2 stack.push(30); // 3 stack.size(); // 3 stack.peek(); // 30 stack.pop(); // 30 stack.peek(); // 20 stack.clear(); stack.isEmpty(); // true
Constraints & Edge Cases
- Handle pop and peek operations on an empty stack
- Ensure proper memory management (no memory leaks)
- The stack should handle any JavaScript data type as elements
Companies:
meta
tcs
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
