
Problem
Solution
Submissions
Implement a stack using an array
Certification: Basic Level
Accuracy: 28.57%
Submissions: 7
Points: 5
Write a C# program to implement a stack data structure using an array. A stack is a linear data structure that follows the Last In First Out (LIFO) principle.
Example 1
- Input:
- Push(10)
- Push(20)
- Push(30)
- Pop()
- Peek()
- IsEmpty()
- Output:
- 30
- 20
- False
- Explanation:
- Step 1: Push 10, 20, and 30 to the stack to get [10, 20, 30].
- Step 2: Pop() removes and returns the top element 30.
- Step 3: Peek() returns the current top element 20 without removing it.
- Step 4: IsEmpty() returns false as the stack still has elements.
Example 2
- Input:
- Push(5)
- Pop()
- Pop()
- IsEmpty()
- Output:
- 5
- Stack Underflow
- True
- Explanation:
- Step 1: Push 5 to the stack to get [5].
- Step 2: First Pop() removes and returns 5.
- Step 3: Second Pop() tries to remove from an empty stack, resulting in "Stack Underflow".
- Step 4: IsEmpty() returns true as the stack is now empty.
Constraints
- The capacity of the stack is fixed and determined at initialization
- 0 ≤ Number of operations ≤ 1000
- 0 ≤ Values pushed to the stack ≤ 10^4
- Time Complexity for all operations: O(1)
- Space Complexity: O(n) where n is the stack capacity
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 elements and a variable to track the top index.
- Implement boundary checks to avoid stack overflow and underflow.
- Initialize the top index to -1 to indicate an empty stack.
- Increment the top index when pushing and decrement when popping.
- Return appropriate error messages or throw exceptions for invalid operations.