Implement Stack using Array
Learning DSA practice problem on Onlearn.
Difficulty: easy.
Topics: Implementing a Stack Using an Array, Data Structures, Stack, Arrays, Time Complexity, Space Complexity, Big O Notation, stack operations, fifo/lifo properties, space complexity, stack, array, time complexity analysis, data structure operations, Stack (LIFO), Stack Operations.
Problem: Implement Stack using Array Implement a basic Stack data structure using an array. The stack should support the following operations: push(x): Inserts element x onto the stack. pop(): Removes and returns the topmost element from the stack. If the stack is empty, an appropriate value (e.g., 1 or raise an error, depending on problem constraints) should be returned/handled. top(): Returns the topmost element of the stack without removing it. If the stack is empty, an appropriate value should be returned/handled. size(): Returns the number of elements currently in the stack. Input Specification The input will consist of a sequence of operations to be performed on the stack. Each operation will be one of the following: push V: Push integer V onto the stack. pop: Pop an element from the stack. top: Get the top element of the stack. size: Get the current size of the stack. Output Specification For pop, top, and size operations, print the result of the operation on a new line. Constraints The maximum number of operations will be up to 10^5. Values V to be pushed will be integers in the range [ 10^9, 10^9]. The maximum capacity of the stack will be 1000. For pop() and top() on an empty stack, you can assume that the test cases will not lead to such scenarios, or return a sentinel value like 1. Sample Test Cases Sample Input Sample Output