Stack

A stack is a data structure that follows the Last In First Out (LIFO) principle. It allows for the addition and removal of elements in a particular order, where the last element added is the first to be removed.

Space Complexity: O(n)
Time Complexity: O(1) for push/pop
Best Case: Ω(1)
Average Case: Θ(1)
Worst Case: O(1)


class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if not self.items:
            return None
        return self.items.pop()

    def peek(self):
        if not self.items:
            return None
        return self.items[-1]

    def is_empty(self):
        return len(self.items) == 0

    def display(self):
        return ' -> '.join(map(str, self.items))

# Example Usage
stack = Stack()
for i in range(20):
    stack.push(random.randint(0, 100))
print(stack.display())

Time Complexity Comparison

Space Complexity Comparison