Tutorialspoint
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
ArraysStackCapgeminiSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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.

Steps to solve by this approach:

 Step 1: Create a class with an array, a top index variable, and a capacity variable.
 Step 2: Initialize the top index to -1 to represent an empty stack.
 Step 3: Implement Push by incrementing the top index and adding the value if the stack is not full.
 Step 4: Implement Pop by returning and decrementing the top index if the stack is not empty.
 Step 5: Implement auxiliary methods like Peek, IsEmpty, and IsFull for stack operations.

Submitted Code :