Implement Stack using Arrays

Stack / Queues Implementation Easy

Implement a Last-In-First-Out (LIFO) stack using an array. The implemented stack should support the following operations: push, pop, peek, and isEmpty.


Implement the ArrayStack class:


void push(int x): Pushes element x onto the stack.

int pop(): Removes and returns the top element of the stack.

int top(): Returns the top element of the stack without removing it.

boolean isEmpty(): Returns true if the stack is empty, false otherwise.




Please note that this section might seem a bit difficult without prior knowledge on what stacks is, we will soon try to add basics concepts for your ease! If you know the concepts already please go ahead to give a shot to the problem. Cheers!

Examples:

Input: ["ArrayStack", "push", "push", "top", "pop", "isEmpty"]

[[], [5], [10], [], [], []]

Output: [null, null, null, 10, 10, false]

Explanation:

ArrayStack stack = new ArrayStack();

stack.push(5);

stack.push(10);

stack.top(); // returns 10

stack.pop(); // returns 10

stack.isEmpty(); // returns false

Input: ["ArrayStack","isEmpty", "push", "pop", "isEmpty"]

[[], [], [1], [], []]

Output: [null, true, null, 1, true]

Explanation: 

ArrayStack stack = new ArrayStack();

stack.push(1);

stack.pop(); // returns 1

stack.isEmpty(); // returns true

Input: ["ArrayStack", "isEmpty"]

[[], []]

Constraints

  • 1 <= numbers of calls made <= 100
  • 1 <= x <= 100

Hints

  • Calling pop() or top() on an empty stack should raise an appropriate exception.
  • Ensure isEmpty() accurately reflects whether the stack has elements.

Company Tags

Epic Games AMD Target MongoDB Activision Blizzard PayPal Goldman Sachs Airbnb Roblox Teladoc Health Siemens Healthineers Byju's Salesforce Alibaba American Express ARM Freshworks Red Hat Broadcom Rockstar Games Intel Docker Twilio Seagate Technology Unity Technologies Google Microsoft Amazon Meta Apple Netflix Adobe TCS Cognizant Accenture Infosys Capgemini Wipro