Implement Stack using Arrays

Stack / Queues Implementation Easy
  • The concept of Last-In-First-Out (LIFO) stacks is widely used in real-world scenarios such as managing function calls in programming languages
  • Each time a function is called, the system 'pushes' contexts onto a call stack
  • When the function is done, the system 'pops' the context off of the stack and restore the state before the call
  • This call stack is fundamental to enabling function calls and recursion in virtually all modern programming languages
  • Similarly, the 'undo' feature in many software applications (like text editors or graphic design tools) is often implemented using a stack

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