๐Ÿ“š 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:

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

#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