Back to Data Structures & Algorithms
2026-02-135 min read

LIFO Principle of Stack (Data Structures & Algorithms)

Learn LIFO Principle of Stack (Data Structures & Algorithms) step by step with clear examples and exercises.

Why This Matters

The LIFO (Last In, First Out) principle is a fundamental concept in computer science that underpins various operations, including function calls, recursion, and implementing stacks. Mastering this principle can help you tackle real-world coding challenges, debug complex code, and excel in interviews.

Understanding the LIFO principle is crucial for mastering data structures and algorithms because it simplifies the management of dynamic data collections. By following the LIFO rule, developers can create efficient solutions for various problems, such as parsing expressions, implementing undo/redo functionality, or simulating real-world scenarios like a game of chess.

Prerequisites

To fully grasp the LIFO principle of stack, you should be comfortable with:

  1. Basic Python syntax and data types (e.g., variables, strings, integers, lists, tuples, dictionaries)
  2. Understanding control structures like loops, conditional statements, and functions
  3. Familiarity with lists and their basic operations (append, extend, pop, etc.)
  4. Knowledge of Python exceptions (try-except blocks)
  5. Understanding the concept of data structures such as arrays and linked lists
  6. Basic understanding of Big O notation to analyze time complexity of algorithms

Core Concept

A stack is a linear data structure that follows the LIFO principle. It operates under two main principles:

  1. Push: Adding an element to the top of the stack
  2. Pop: Removing an element from the top of the stack

Stacks are often visualized as a pile of dishes, where the last dish added is the first one taken out. In programming terms, a stack can be implemented using arrays or linked lists.

Stack Operations (Expanded)

  1. push(item): Adds an item to the top of the stack
  2. pop(): Removes and returns the topmost item from the stack
  3. peek(): Returns the topmost item without removing it
  4. is_empty(): Checks if the stack is empty or not
  5. size(): Returns the number of elements in the stack
  6. min(): Returns the minimum value in the stack (optional)
  7. max(): Returns the maximum value in the stack (optional)
  8. top(): Returns the top element without removing it (optional, not all implementations may have this method)

Python Stack Implementation (Expanded)

class Node:
def __init__(self, data):
self.data = data
self.next = None

class Stack:
def __init__(self):
self.top = None

def push(self, item):
new_node = Node(item)
if not self.top:
self.top = new_node
else:
new_node.next = self.top
self.top = new_node

def pop(self):
if not self.top:
raise IndexError("Pop from an empty stack")
popped_item = self.top.data
self.top = self.top.next
return popped_item

def peek(self):
if not self.top:
raise IndexError("Peek at an empty stack")
return self.top.data

def is_empty(self):
return not self.top

def size(self):
current = self.top
count = 0
while current:
count += 1
current = current.next
return count

def min(self):
if not self.is_empty():
min_value = self.top.data
current = self.top
while current.next:
if current.next.data < min_value:
min_value = current.next.data
current = current.next
return min_value
else:
raise ValueError("Stack is empty")

def max(self):
if not self.is_empty():
max_value = self.top.data
current = self.top
while current.next:
if current.next.data > max_value:
max_value = current.next.data
current = current.next
return max_value
else:
raise ValueError("Stack is empty")

Worked Example

Let's create a simple stack and perform some operations:

stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print("Top element:", stack.peek()) # Output: 3
stack.pop()
print("Top element after pop:", stack.peek()) # Output: 2
print("Stack size:", stack.size()) # Output: 2

Common Mistakes

  1. Forgetting to check if the stack is empty before performing operations: This can lead to runtime errors.
def pop(self):
if not self.is_empty():
popped_item = self.top.data
self.top = self.top.next
return popped_item
else:
raise IndexError("Pop from an empty stack")
  1. Not handling exceptions when popping an empty stack: Proper exception handling ensures that your program does not crash unexpectedly.
  1. Implementing a stack using lists without considering edge cases: Failing to consider edge cases like pushing or popping multiple items at once can lead to incorrect results.
def push_multiple(self, items):
for item in items:
self.push(item)
  1. Incorrect use of push and append: Be aware that push adds an element to the top of the stack, while append adds it to the end of a list (not a stack).
  1. Not properly handling minimum and maximum values in stacks with mixed data types: Ensure that you handle cases where stacks contain both numeric and non-numeric elements.
  1. Using an array as a stack without implementing push, pop, peek, etc.: While it is possible to use an array as a simple implementation of a stack, it lacks the necessary methods for efficient manipulation.

Practice Questions

  1. Implement a function that checks if a given expression is balanced (e.g., ((())) is balanced, but (())) is not).
def is_balanced(expression):
stack = Stack()
for char in expression:
if char == '(':
stack.push(char)
elif char == ')':
if stack.is_empty() or stack.pop() != '(':
return False
return stack.is_empty()
  1. Write a Python program that implements a postfix calculator using a stack.
  1. Given an array of integers, implement a function that finds the maximum sum of subarrays with unique elements (e.g., [1, 2, 3, 4] has subarrays: [1], [2], [3], [4], [1, 2], [3, 4], but not [1, 2, 3] or [1, 2, 4]).
def max_unique_subarray(numbers):
if len(numbers) == 0:
return 0

current_sum = numbers[0]
max_sum = numbers[0]
seen_numbers = {numbers[0]}

for i in range(1, len(numbers)):
if numbers[i] not in seen_numbers:
current_sum += numbers[i]
seen_numbers.add(numbers[i])
else:
max_sum = max(max_sum, current_sum)
current_sum = numbers[i]
seen_numbers = {numbers[i]}

return max(max_sum, current_sum)

FAQ

How can I implement a stack using linked lists?

To create a stack using linked lists, you'll need to define Node and Stack classes. Each node should contain data and a reference to the next node, while the Stack class will manage the top of the stack and other operations like push, pop, peek, etc.

What is the time complexity of common stack operations in Python?

  1. Push: O(1) (constant time)
  2. Pop: O(1) (constant time)
  3. Peek: O(1) (constant time)
  4. Is empty: O(1) (constant time)
  5. Size: O(n) (linear time, as iterating through a linked list requires traversing all elements)
  6. Min/Max: O(n) (linear time, as finding the minimum or maximum requires iterating through all elements in the stack)
LIFO Principle of Stack (Data Structures & Algorithms) | Data Structures & Algorithms | XQA Learn