Skip to main content

Implement stack using array

Problem​

Write a program to implement a Stack using Array. Your task is to use the class as shown in the comments in the code editor and complete the functions push() and pop() to implement a stack.

Examples:​

Example 1:

Input: 
push(2)
push(3)
pop()
push(4)
pop()
Output: 3, 4
Explanation:
push(2) the stack will be {2}
push(3) the stack will be {2 3}
pop() poped element will be 3,
the stack will be {2}
push(4) the stack will be {2 4}
pop() poped element will be 4

Example 2:

Input: 
pop()
push(4)
push(5)
pop()
Output: -1, 5

Your task:​

You are required to complete two methods push() and pop(). The push() method takes one argument, an integer 'x' to be pushed into the stack and pop() which returns an integer present at the top and popped out from the stack. If the stack is empty then return -1 from the pop() method.

  • Expected Time Complexity: O(1)O(1) for both push() and pop()
  • Expected Auxiliary Space: O(1)O(1) for both push() and pop()

Constraints:​

  • 1<=Q<=1001 <= Q <= 100
  • 1<=x<=1001 <= x <= 100

Solution​

Python​

def push(self,data):
self.arr.append(data)
return self.arr

def pop(self):
if len(self.arr) == 0:
return -1
else:
return self.arr.pop()

Java​

void push(int a) {
if (top < 999) {
top++;
arr[top] = a;
}
}

int pop() {
if (top >= 0) {
int poppedElement = arr[top];
top--;
return poppedElement;
}
else {
return -1;
}
}

C++​

void MyStack :: push(int x) {
if (top < 999) {
top++;
arr[top] = x;
}
}

int MyStack :: pop() {
if (top >= 0) {
int poppedElement = arr[top];
top--;
return poppedElement;
}
else {
return -1;
}
}

C​

void push(struct Stack* stack, int item) {
if (stack->top != stack->capacity - 1) {
stack->top++;
stack->array[stack->top] = item;
}
}

int pop(struct Stack* stack) {
if (stack->top == -1) {
return -1;
}
int item = stack->array[stack->top];
stack->top--;
return item;
}
  • Time Complexity: O(1)O(1), for both push() and pop()
  • Auxiliary Space: O(1)O(1), for both push() and pop()