What I Learned Today: Mastering Stacks and Balanced Parentheses in Python 🐍

kasumbi philkasumbi phil
2 min read

Date: Today’s session was all about stacks and practical problem solving.


🚀 A Quick Recap of My Progress

Today, I dove into the world of stacks — a powerful linear data structure that follows the Last In, First Out (LIFO) principle. I learned how to use basic stack operations like:

  • push() – Add an element to the top of the stack

  • pop() – Remove the element from the top of the stack

  • peek() (often called top or stack[-1]) – Look at the top element without removing it


🧩 Real-World Problem: Validating Balanced Parentheses

To solidify my understanding of stacks, I tackled a classic coding challenge: checking whether a string of parentheses is balanced. This means that every opening bracket like (, {, or [ must have a corresponding and correctly ordered closing bracket: ), }, or ].


📜 The Problem-Solving Steps I Followed:

Copy

Copy

1. Traverse the string character by character.
2. If you encounter an opening parenthesis, push it to the stack.
3. If you encounter a closing parenthesis, check if there is a corresponding opening parenthesis at the top of the stack.
   - If there is, pop it from the stack.
   - If not, the string is unbalanced.
4. After traversing the whole string, if the stack is empty, the parentheses are balanced.

🧪 Here’s the Python Code I Wrote

Copy

Copy

#solving problems using stack 
chars = "(())(()){}}"

stack = []

# mapping of closing to opening 
pairs = {
    ')': '(',
    '}': '{',
    ']': '['
}

for char in chars:
    if char in '({[':
        stack.append(char)
    elif char in ')}]':
        if not stack:
            print("Unbalanced: No matching opening for", char)
            break
        elif stack[-1] == pairs[char]:
            stack.pop()
        else:
            print("Unbalanced: Expected", pairs[char], "but found", stack[-1])
            break
else:
    if not stack:
        print("✅ All parentheses are balanced!")
    else:
        print("❌ Unbalanced: Some opening parentheses were not closed:", stack)

🧠 What I Learned:

  • Stacks are incredibly useful for problems involving nested structure or reversing order.

  • The stack.pop() method is great for backtracking to the most recent opening parenthesis.

  • The Python else block on a for loop was new to me! It only runs when the loop completes without a break.

0
Subscribe to my newsletter

Read articles from kasumbi phil directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

kasumbi phil
kasumbi phil