Valid Parentheses Problem Solution with Stack

🚀 Day 17 — Valid Parentheses Continuing the Stack pattern. 🧩 Problem solved: Valid Parentheses 💻 Platform: LeetCode (#20) Given a string containing only '(', ')', '{', '}', '[' and ']', determine if the input string is valid. Example: Input: s = "()[]{}" Output: true Input: s = "([)]" Output: false --- 🧠 First Thought (Brute Force) Repeatedly remove adjacent matching pairs like "()", "[]", "{}" until no more removals are possible. If the string becomes empty → valid. But this leads to O(n²) complexity. Clearly inefficient. --- ⚡ Optimal Approach — Stack (via StringBuilder) Key Insight: A closing bracket must always match the most recently seen opening bracket. That’s exactly what a Stack is built for — LIFO. Twist: Instead of Stack<Character>, I used StringBuilder as the stack. Same logic, lighter overhead. Steps: • Iterate through each character • If top of StringBuilder matches current closing bracket → pop (deleteCharAt) • Otherwise → push (append) • If StringBuilder is empty at end → valid Time Complexity: O(n) Space Complexity: O(n) 🔍 What this problem reinforced: ✔ Stack is the go-to structure when order + matching matters ✔ LIFO logic maps perfectly to nested bracket structures ✔ StringBuilder can simulate a stack — not just for string building! This problem made the Stack pattern click in a new way. Solutions are available here: 🔗https://lnkd.in/gW8atfqw Day-17 complete. ✅ #DSA #Java #LeetCode #Stack #ProblemSolving #CodingJourney #LearningInPublic

To view or add a comment, sign in

Explore content categories