Problem: Given a string containing ()[]{}, determine if the parentheses are valid. A string is valid if brackets close in the correct order and type. ⬇️ ⬇️ ⬇️ My initial intuition: 😎 Thought of using a stack immediately — push openings, pop on closings. ☠️ But the first few implementations broke on tricky cases like ([)]. 🤡 I was popping and comparing in the wrong order and couldn’t figure out how to validate the pairings cleanly. ⬇️ ⬇️ ⬇️ After careful debugging: 😎 Discovered that flipping my mapping made the logic much simpler: { ')': '(', ']': '[', '}': '{' } 💡 This way, every closing bracket directly tells me which opening it expects. 😎 The stack now works perfectly — last in, first out — catching even the toughest edge cases. 🌟🌟🌟 learned about little micro optimizations: -> to create a local reference of the map helps with access times. -> not unravelling map with .values() calls, instead created a set of opening parenthesis. ✅ Intuition was right this time. 😅 Execution... not so much. #LeetCode #ProblemSolving #Python #LearningJourney #Coding
Validating Parentheses with Stack and Map
More Relevant Posts
-
DAY-1:CODING CHALLENGE 1.Longest common Prefix substring from given string as input 2.3SUM problem Started with BRUTE-FORCE → checked every triplet. 😀 Worked 😇 but SLOW for big arrays (O(n³)) → TIME LIMIT EXCEEDED. Faced errors along the way: 'int object not iterable' → I wrote sorted(a,b,c) instead of sorted([a,b,c]). 'unhashable type: list' → Tried adding list to set. Fixed by converting to tuple. LOGICAL BUG → Return inside the loop returned early. Fixed by moving return outside. Finally moved to OPTIMAL TWO-POINTER APPROACH: Sort array first. Use two pointers to find pairs for target -nums[i]. Skip duplicates carefully. Complexity reduced to O(n²). 💡 Lessons learned: small syntax mistakes can cause big errors, immutable types are key for sets, and proper pointer logic makes code efficient. #Python #Algorithms #LeetCode #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
💡 Day 37 of 100 — Minimum Operations to Convert All Elements to Zero (#LeetCode 3542) Today’s problem was an interesting one short in code, but deeper in logic. It was one of those problems where the intuition slowly unfolds as you play with examples. 🧠 What I figured out This problem is all about monotonic stacks a pattern that helps you process elements in increasing or decreasing order efficiently. The key idea: Every time the current number is greater than what’s on top of the stack, it represents a new “operation” needed. By maintaining a non-decreasing stack, you avoid unnecessary repetitions and count exactly when new operations are required. 💻 My thought process At first, I tried to simulate each operation directly which got messy. Then I realized this could be solved cleanly using a stack that tracks when a new increase appears in the sequence. Every rise means one more operation, and when numbers fall, you just pop from the stack. 📊 Complexity: Time — O(n) Space — O(n) 💬 Reflection This one reminded me how often elegant ideas hide in short problems. It’s not about long code it’s about clarity of thought. Sometimes, a single stack can tell the whole story. #100DaysOfLeetCode #Day37 #LeetCodeJourney #Coding #ProblemSolving #Python #DSA
To view or add a comment, sign in
-
-
Day 72: Partition List 🔗 I'm back to linked lists on Day 72 of #100DaysOfCode by solving "Partition List." The challenge is to rearrange a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x, while preserving the original relative order within each partition. My solution uses a two-list approach with dummy nodes: Creation of Two Lists: I initialize two separate dummy nodes: less_dummy and greater_dummy. Partitioning: I iterate through the original list once. If a node's value is less than x, I append it to the less list; otherwise, I append it to the greater list. This inherently preserves the relative order within each group. Merging: After the single pass, I set the next pointer of the tail of the less list to the head of the greater list (less_tail.next = greater_dummy.next). Crucially, I set the tail of the greater list to None to prevent cycles (greater_tail.next = None). This single-pass method achieves an optimal O(n) time complexity and O(1) extra space complexity (excluding the new nodes being rearranged). My solution was accepted with 100% runtime efficiency! #Python #DSA #Algorithms #LinkedList #100DaysOfCode #ProblemSolving
To view or add a comment, sign in
-
-
🚀 DSA Progress – Day 108 ✅ Problem #3304: Find the K-th Character in String Game I 🧠 Difficulty: Easy | Topics: String, Simulation, Character Manipulation 🔍 Approach: Implemented an iterative string-building simulation to generate characters step by step until the length of the string reaches k. Step 1 (Initialization): Start with the base string result = "a". Step 2 (Expansion Rule): For every iteration, create a new version of the string by incrementing each character of the current string ('a' → 'b', 'b' → 'c', … 'z' → 'a') and append it to the original string. Step 3 (Stop Condition): Continue expanding until the string length becomes at least k. Step 4 (Answer): Return the (k-1)th character from the final string (since Python uses 0-based indexing). 🕒 Time Complexity: O(k)-we generate characters until the length reaches k. 💾 Space Complexity: O(k) — the built string grows proportionally with k. 📁 File: https://lnkd.in/g4pnXWep 📚 Repo: https://lnkd.in/g8Cn-EwH 💡 Learned: This problem helped reinforce the idea of string growth patterns and character transformation using ord() and chr(). It was a great exercise in understanding simulation-based problems, where you build patterns step by step until reaching the desired condition. Also, it improved my clarity on how to handle alphabet wrapping ('z' → 'a') efficiently in Python. ✅ Day 108 complete — leveled up from 'a' to 'z' and looped back like a pro! 🔠⚡💪 #LeetCode #DSA #Python #Strings #Simulation #CharacterManipulation #DailyCoding #InterviewPrep #GitHubJourney
To view or add a comment, sign in
-
Day 31 / 100 – Add Strings (LeetCode #415) Today’s challenge was all about simulating manual addition without using any built-in integer conversions. Given two numbers as strings, the task was to return their sum — also as a string. This problem really emphasized the importance of breaking problems into small, logical steps rather than relying on shortcuts. 🔍 Key Learnings Recreated the digit-by-digit addition process using ASCII values. Practiced handling carry-over efficiently while iterating backward. Strengthened my understanding of string manipulation and arithmetic logic. 💭 Thought of the Day True problem-solving isn’t about using built-ins — it’s about understanding how things work underneath. Today reminded me that mastery grows when we rebuild the basics from scratch, not when we avoid them. 🔗 Problem Link: https://lnkd.in/gHMt9vj9 #100DaysOfCode #Day31 #LeetCode #Python #ProblemSolving #StringManipulation #Algorithms #DataStructures #CodingChallenge #CodeEveryday #TechGrowth #LearningJourney
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 104 Problem: Flatten Binary Tree to Linked List 🌳➡️📄 This problem is a beautiful blend of tree traversal and pointer manipulation. The goal is to transform a binary tree into a linked list following preorder traversal, while modifying the tree in-place. 🧠 Problem Summary: You're given the root of a binary tree. Your task → Flatten the tree into a linked list such that: Each node’s right pointer acts as the “next” pointer. Each node’s left pointer is always None. The resulting order must follow preorder traversal: Root → Left → Right ⚙️ My Approach: I used a recursive DFS approach that processes nodes in a way that supports pointer restructuring: 1️⃣ Flatten left subtree 2️⃣ Flatten right subtree 3️⃣ If the current node has a left subtree: Temporarily store root.right Move root.left to root.right Nullify the left pointer Traverse to the end of this new right chain Attach the original right subtree there This ensures the node order becomes preorder while maintaining pointer correctness. 📌 Key Observations: Although preorder is Root → Left → Right, the flattening requires processing children first. Doing operations in-place ensures optimal space usage. Traversing to the end of the newly attached right subtree ensures that both left and right parts remain connected in correct order. 📈 Complexity: Time: O(n) — Each node is visited once Space: O(h) — Recursion stack (height of the tree) ✨ Key Takeaway: Flattening a binary tree becomes simple once you understand pointer realignment. First flatten both subtrees → then stitch them together → and the final structure becomes a clean preorder linked list. 🌳➡️🪜 🔖 #DSA #100DaysOfCode #Day104 #BinaryTrees #PreorderTraversal #TreeFlattening #Recursion #LeetCode #ProblemSolving #Python #CodingJourney #TechCommunity #LearningEveryday
To view or add a comment, sign in
-
-
Day 36 / 100 – Longest Palindromic Substring (LeetCode #5) Today’s challenge focused on String Manipulation — finding the longest palindromic substring within a given string. At first, it felt tricky to handle all the possible substrings, but then I learned to expand around the center, checking for symmetry on both sides. This approach makes the solution both logical and efficient. This problem reinforced how clarity in logic often comes from recognizing patterns, and that even complex problems can be broken into smaller, mirror-like checks. 🔍 Key Learnings Expanding around the center efficiently checks for palindromes in O(n²) time. Always consider both even and odd length palindromes. String problems often rely on clear thinking more than heavy algorithms. 💭 Thought of the Day Problem-solving isn’t about rushing for the answer — it’s about exploring the structure of the challenge. Palindromes taught me patience, symmetry, and the art of looking for balance in both logic and code. 🔗 Problem Link: https://lnkd.in/gSe-ygD8 #100DaysOfCode #Day36 #LeetCode #Python #StringManipulation #ProblemSolving #Algorithms #CodingChallenge #CleanCode #CodeEveryday #LearningJourney #DataStructures #Optimization
To view or add a comment, sign in
-
-
Find the Length of Last Word — Problem My today's LeetCode small challenge. Sometimes we miss little things and end up hardcoding a function that already exists,(I am talking about split( ) ). That's exactly what happened while I was solving the Length of Last Word problem, where you are given a string of words and have to find the length of the last word in that string. So, the solution was simple: use the split( ) method in Python , it removes empty spaces ,then just call the len( ) function on the last word of the string. But what I was doing was hardcoding the splitting of the string into words. It’s where Reyan Arshad told me that I have figured out the solution, have you? I said, “Not yet, give me a hint,” and he said, “Here we have to use a method that automatically gives a list of words only, without spaces.” As soon as I read the hint, and specifically the word "method" it clicked — the split( ) method — and the solution was reached. P.S. It’s my second day of LeetCode problem-solving. Here’s my LeetCode profile 👇 https://lnkd.in/daSxpGmi 🔗 Connect if you are also solving LeetCode problems — I’ll be sharing simple explanations of the problem solutions here. #datastructures #algorithms #LeetCode
To view or add a comment, sign in
-
-
I recently revisited a project I built a while back, a 𝗣𝘆𝘁𝗵𝗼𝗻 𝘀𝗼𝗹𝘃𝗲𝗿 for the Bridges (Hashiwokakero) puzzle. 🧩 For those who haven’t seen it, Bridges is a logic puzzle where you connect islands with bridges according to specific rules. The idea came from a weekly tradition with my mum, solving the puzzle together over lunch. After we got pretty good at it, I got curious: could I teach a computer to do this too? What started as a fun side project turned into a deeper dive into algorithms and search optimisation, using recursive backtracking and graph-based connectivity checks. It’s a simple project, but one that means a lot to me. 🔗 Check it out here: https://lnkd.in/eJ_jwwud I’ve also attached a short video showing the solver in action, just terminal output, but it’s fun to see it work! #Python #Algorithms #ProblemSolving
To view or add a comment, sign in
-
🚀 Solved LeetCode 3234: Count Substrings with Dominant Ones! 🧠 Just tackled a challenging substring problem: 3234. Count the Number of Substrings With Dominant Ones. The goal is to find all substrings where the count of '1's is greater than or equal to the square of the count of '0's. A simple O(N²) approach is too slow, so a more optimized strategy is needed. My Approach: Key Insight: The condition ones >= zeros² means the number of zeros in any valid substring is small (at most √N). This is the key to optimization. Fix the Endpoint: I iterate through the string, fixing the end of the potential substring. "Zero-Hopping" Technique: From the end, I iterate backward, but instead of going one by one, I "hop" from each '0' to the previous '0'. A precomputed array makes this hop O(1). Efficient Counting: At each hop, I calculate the number of valid start positions in the segment between the two zeros, bringing the total time complexity down to O(N√N). This was a great puzzle in finding the bottleneck and building an algorithm around it! 🔗 Problem Link: https://lnkd.in/gpmZdskg #LeetCode #Coding #Algorithm #Python #ProblemSolving #SoftwareEngineering #Optimization #LeetCode #Coding #Algorithm #Python #Programming #InterviewPrep
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development