Explorer
Node.js

Implement a Stack class with `push(val)`, `pop()`, `peek()`, `isEmpty()`, and `size()` methods.

Problem Statement

Implement a Stack class with `push(val)`, `pop()`, `peek()`, `isEmpty()`, and `size()` methods.

Complexity

Time Complexity: -

Space Complexity: -

Hints

šŸ’” Hint 1: A stack follows Last-In-First-Out (LIFO) principle. šŸ’” Hint 2: Use an array internally. push() adds to end, pop() removes from end. šŸ’” Hint 3: peek() returns the last element without removing it. āœ… Solution: ```javascript class Stack { constructor() { this.items = []; } push(val) { this.items.push(val); } pop() { return this.items.pop(); } peek() { return this.items[this.items.length - 1]; } isEmpty() { return this.items.length === 0; } size() { return this.items.length; } } ```

Implement a Stack

Medium
Implement a Stack class with `push(val)`, `pop()`, `peek()`, `isEmpty()`, and `size()` methods.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"peek":3,"popped":3,"size":2,"isEmpty":false}