
Problem
Solution
Submissions
Stack using Arrays
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a JavaScript program to implement a stack data structure using arrays. A stack is a linear data structure that follows the Last In First Out (LIFO) principle. The stack should support basic operations like push (add element to top), pop (remove element from top), peek/top (get top element without removing), isEmpty (check if stack is empty), and size (get number of elements).
Example 1
- Input: Push operations: [1, 2, 3, 4], Pop operation called twice
- Output: Stack contains [1, 2], popped elements are 4 and 3
- Explanation:
- Initially stack is empty [], then push 1, 2, 3, 4 sequentially.
- Stack becomes [1, 2, 3, 4].
- Pop operation removes 4, stack becomes [1, 2, 3].
- Pop operation removes 3, stack becomes [1, 2].
- Initially stack is empty [], then push 1, 2, 3, 4 sequentially.
Example 2
- Input: Push operations: [10, 20], Peek operation, Pop operation, isEmpty check
- Output: Peek returns 20, pop returns 20, stack contains [10], isEmpty returns false
- Explanation:
- Initially stack is empty [], push 10 and 20.
- Stack becomes [10, 20].
- Peek operation returns 20 without removing it.
- Pop operation removes and returns 20, stack becomes [10].
- isEmpty check returns false since stack has one element.
- Initially stack is empty [], push 10 and 20.
Constraints
- The stack should handle integer values
- Maximum stack size can be up to 10^4 elements
- Pop and peek operations on empty stack should return null or undefined
- Time Complexity: O(1) for all operations
- Space Complexity: O(n) where n is the number of elements
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use an array to store stack elements where the last element represents the top
- Maintain a pointer or use array length to track the top position
- For push operation, add element to the end of array
- For pop operation, remove and return the last element
- For peek operation, return the last element without removing it
- Use array length to check if stack is empty and get size