Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Implement Stack Using Array

Basic Acceptance 54.76% Points 10.00

Write a program to implement a Stack using an array. Complete the push() and pop() methods as described below. The push(x) method takes an integer x as input and adds it to the stack. The pop() method removes and returns the top element of the stack. If the stack is empty, the pop() method should return -1.

Input is provided as a series of queries:

  1. Type 1 x: Pushes the integer x onto the stack.
  2. Type 2: Pops the top element from the stack and prints it. If the stack is empty, it prints -1.
Examples
Example 1

Example 1

Input: 1 5 1 15 2 2 2

Output: 15 5 -1

Explanation: The first query 1 5 means push 5 onto the stack. The stack becomes [5]. The second query 1 15 means push 15 onto the stack. The stack becomes [5, 15]. The third query 2 means pop the top element, which is 15. The stack becomes [5]- Output 15. The fourth query 2 means pop the top element, which is 5. The stack becomes []- Output 5. The fifth query 2 means pop the top element, but the stack is empty. Output -1.

Example 2

Example 2

Input: 1 10 1 20 2 2

Output: 20 10

Explanation: The first query 1 10 means push 10 onto the stack. The stack becomes [10]. The second query 1 20 means push 20 onto the stack. The stack becomes [10, 20]. The third query 2 means pop the top element from the stack, which is 20. The stack becomes [10]- Output 20. The fourth query 2 means pop the top element from the stack, which is 10. The stack becomes []- Output 10.

Hints
Hint 1
Expected Time Complexity: O(1)
Hint 2
Expected Space Complexity: O(1)
Constraints
  • 1 <= numbers of calls made to push, pop <= 100
  • 1 <= x <= 100
Companies
Visa Goldman Sachs Qualcomm
Topics
Stack
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions