🚀Day 16 of #128DaysOfCode Solved a classic stack-based problem today! 🔍 Problem: Validate whether a string containing brackets "() {} []" is properly balanced. 💡 Approach: Used a Stack (LIFO) to track opening brackets and match them with corresponding closing brackets. - Push opening brackets - On closing bracket → check top of stack - If mismatch or stack is empty → invalid - At the end, stack should be empty This problem highlights how stacks are perfect for handling nested structures and order-based validation 🧠 Key Learnings: ✔ Strengthened understanding of Stack data structure ✔ Learned how to handle edge cases like mismatched and unordered brackets ✔ Improved problem-solving approach for string-based questions ⏱ Complexity: Time → O(n) Space → O(n) Consistency is the key 🔥 On to Day 17 💪 #DSA #Java #LeetCode #Stack #ProblemSolving #CodingJourney #PlacementsPreparation
Validating Balanced Brackets with Stacks in Java
More Relevant Posts
-
🚀 Day 5 – Code Wild Kickoff Series: Reverse Linked List 🔄 Today’s challenge focused on one of the most fundamental and frequently asked data structure problems: Reversing a Singly Linked List. 🧩 Problem Statement Given the beginning of a singly linked list head, reverse the list and return the new beginning of the list. 📌 Examples • Input: [0, 1, 2, 3] Output: [3, 2, 1, 0] • Input: [] Output: [] 📌 Constraints • 0 <= length of the list <= 1000 • -1000 <= Node.val <= 1000 💡 Approach The idea is to reverse the direction of the next pointers while traversing the list. 1. Initialize • prev = null • curr = head 2. Iterate through the list • Store the next node: nextTemp = curr.next • Reverse the pointer: curr.next = prev • Move prev and curr one step forward. 3. Return • When traversal ends, prev becomes the new head of the reversed list. ✅ Edge Cases Handled • Empty list (head == null) → Returns null. • Single node list → Remains unchanged. • General case → All links are reversed in place with O(n) time and O(1) space complexity. #Day5 #CodeWild #100DaysOfCode #DSA #LinkedList #Java #CodingJourney #TechLearning #InterviewPrep
To view or add a comment, sign in
-
-
🚀 Day 44 of my #100DaysOfCode Journey Today, I solved the LeetCode problem: Find the Least Frequent Digit Problem Insight: Find the digit (0–9) that appears the least number of times in a given number. Approach: • Used a frequency array of size 10 to store digit counts • Extracted digits using modulo and division • Traversed the frequency array to find the minimum occurring digit • Returned the smallest digit in case of tie Time Complexity: • O(n) Space Complexity: • O(1) (fixed size array of 10) Key Learnings: • Arrays are more efficient than HashMap when range is limited • Digit extraction using % 10 is very useful in number problems • Keeping track of minimum efficiently avoids extra passes Takeaway: Simple logic + right data structure = clean and optimal solution #DSA #Java #LeetCode #100DaysOfCode #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
🚀 08/04/26 — Stack Foundations: Balancing Parentheses with Precision Today was a productive session where I successfully implemented the Valid Parentheses (LeetCode 20) challenge. This problem is a fundamental exercise in using the Stack data structure to manage nested relationships and maintain order-based logic. 🧱 The Valid Parentheses Logic The goal is to determine if an input string containing (, ), {, }, [ and ] is valid based on whether every open bracket is closed by the correct type and in the correct order. The Stack Strategy: Pushing: As I iterate through the string, whenever I encounter an opening bracket—(, {, or [—I push it onto the stack. Popping and Matching: When I encounter a closing bracket, I first check if the stack is empty. If it is, the string is invalid. Otherwise, I pop the top element from the stack and compare it to the current closing bracket. Validation: If the brackets don't match (e.g., a ) following a {), the function immediately returns false. Final Check: After the loop finishes, the string is only valid if the stack is completely empty, ensuring all open brackets were properly closed. Complexity Metrics: Time Complexity: O(n) where n is the length of the string, as we perform a single linear pass. Space Complexity: O(n) in the worst case where the string contains only opening brackets, requiring them all to be stored in the stack. 📈 Consistency Report Coming off my 50-day streak milestone, today's focus on stacks feels like a solid pivot from the sliding window and array patterns I've been mastering recently. The logic used here is remarkably similar to the structural checks I used in the "String Search" and "Mountain Array" problems earlier this month, where maintaining a specific state across iterations was key. Huge thanks to Anuj Kumar (a.k.a CTO Bhaiya on YouTube) for the continuous inspiration. Every new data structure I master adds another layer to my problem-solving toolkit! My tested O(n) stack-based implementation is attached below! 📄👇 #DSA #Java #Stack #ValidParentheses #DataStructures #Complexity #Consistency #LearningInPublic #CTOBhaiya
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟓𝟖 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on finding two numbers in a sorted array that add up to a target. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Two Sum II – Input Array Is Sorted 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 • Used two pointers: • One at the beginning (left) • One at the end (right) • Calculated sum of both elements Logic: • If sum == target → return indices • If sum < target → move left pointer forward • If sum > target → move right pointer backward This works because the array is already sorted. 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • Sorting enables two-pointer optimization • Two pointers reduce time complexity from O(n²) to O(n) • Direction of movement depends on comparison with target • Index-based problems often become simpler with sorted data 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Time: O(n) • Space: O(1) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 When data is sorted, two pointers can turn a complex problem into a simple one. 58 days consistent 🚀 On to Day 59. #DSA #Arrays #TwoPointers #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
🚀 LeetCode Challenge 19/50 💡 Approach: Horizontal Scanning The sorting-based approach costs O(S log n). Instead, I used Horizontal Scanning — take the first string as the prefix and keep shrinking it until every string agrees. No sorting, no extra space! 🔍 Key Insight: → Start with strs[0] as the full prefix candidate → For each next string, shrink prefix from the right until it matches → If prefix becomes empty at any point → return "" → What's left is the longest common prefix! 📈 Complexity: ❌ Sort-based → O(S log n) Time ✅ Horizontal Scan → O(S) Time, O(1) Space where S = total characters across all strings The smartest solutions don't always need fancy data structures — sometimes a simple shrinking window does the job perfectly! 🪟 #LeetCode #DSA #StringManipulation #Java #ADA #PBL2 #LeetCodeChallenge #Day19of50 #CodingJourney #ComputerEngineering #AlgorithmDesign #LongestCommonPrefix
To view or add a comment, sign in
-
-
Day 67/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Subsets II Another classic backtracking problem with a twist (duplicates). Problem idea: Generate all possible subsets (power set), but avoid duplicate subsets. Key idea: Backtracking + sorting to handle duplicates. Why? • We need to explore all subset combinations • Duplicates in input can lead to duplicate subsets • Sorting helps us skip repeated elements efficiently How it works: • Sort the array first • At each step, add current subset to result • Iterate through elements • Skip duplicates using condition: 👉 if (i > start && nums[i] == nums[i-1]) continue • Choose → recurse → backtrack Time Complexity: O(2^n) Space Complexity: O(n) recursion depth Big takeaway: Handling duplicates in backtracking requires careful skipping logic, not extra data structures. This pattern appears in many problems (subsets, permutations, combinations). 🔥 Day 67 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #Backtracking #Recursion #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
🚀Day 40 LeetCode 1161 – Maximum Level Sum of a Binary Tree Ever wondered how to find the level of a binary tree with the maximum sum of node values? 🤔 Here’s the idea: We traverse the tree level by level (BFS) and compute the sum at each level. The trick is to keep track of the maximum sum and return the smallest level where this occurs. 💡 Key Insight: Level-order traversal (using a queue) naturally processes nodes one level at a time, making it perfect for this problem. 🔧 Approach: ✔ Use a queue for BFS ✔ For each level: • Calculate sum of nodes ✔ Track maximum sum and corresponding level 🔥 Takeaway: Whenever a problem involves levels in a tree, think BFS first — it often leads to the cleanest solution. #LeetCode #DataStructures #Java #CodingInterview #BinaryTree #BFS #ProblemSolving
To view or add a comment, sign in
-
-
#100DaysOfCode | Day 2 of my LeetCode challenge. Today’s problem: 1365. How Many Numbers Are Smaller Than the Current Number. While the problem seems simple, it’s a perfect example of how choosing the right data structure can drastically change performance. Here is how I broke it down: 1. The Brute Force Approach The most simple and easy way is to use nested loops to compare every number with every other number. Logic: For each element, loop through the entire array and count smaller values. Time Complexity: O(N^2) Space Complexity: O(N) (to store the result) 2. The Sorting + HashMap Approach A more scalable way is to sort the numbers. In a sorted array, a number's index is equal to the count of numbers smaller than it. Logic: Clone the array, sort it, and store the first occurrence of each number in a HashMap. Time Complexity: O(N log N) (due to sorting) Space Complexity: O(N) (to store the map) Use - Works for any range of numbers (including very large or negative ones). 3. The Frequency Array (Counting Sort Logic) Since the problem constraints were small (0 to 100), this is the most optimized solution. Logic: Count the frequency of each number using an array of size 101, then calculate a running prefix sum. Time Complexity: O(N) (Linear time) Space Complexity: O(1) (The frequency array size is constant) #LeetCode #100DaysOfCode #Java #SoftwareEngineering #DataStructures #Algorithms
To view or add a comment, sign in
-
Day 95 of #365DaysOfLeetCode Challenge Today’s problem: **Path Sum III (LeetCode 437)** This one looks like a typical tree problem… but the optimal solution introduces a powerful concept: **Prefix Sum + HashMap in Trees** 💡 **Core Idea:** Instead of checking every possible path (which would be slow), we track **running sums** as we traverse the tree. 👉 If at any point: `currentSum - targetSum` exists in our map → we’ve found a valid path! 📌 **Approach:** * Use DFS to traverse the tree * Maintain a running `currSum` * Store prefix sums in a HashMap * Check how many times `(currSum - targetSum)` has appeared * Backtrack to maintain correct state ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Prefix Sum isn’t just for arrays — it can be **beautifully extended to trees**. This problem completely changed how I look at tree path problems: 👉 From brute-force traversal → to optimized prefix tracking 💭 **Key takeaway:** When a problem involves “subarray/paths with a given sum,” think: ➡️ Prefix Sum + HashMap #LeetCode #DSA #BinaryTree #PrefixSum #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
Today I solved LeetCode 958 – Check Completeness of a Binary Tree. 🧩 Problem Summary: Given the root of a binary tree, determine if it is a complete binary tree. A complete binary tree is defined as: All levels are completely filled except possibly the last level In the last level, nodes are as far left as possible 💡 Key Concepts Used: Binary Trees Breadth First Search (BFS) Queue data structure Tree properties 🧠 Approach: Use BFS (level order traversal) with a queue. Traverse nodes level by level. Once a null node is encountered: All following nodes must also be null. If a non-null node appears after a null, the tree is not complete. Otherwise, the tree satisfies completeness. ⏱ Time Complexity: O(N) — Each node is visited once. 📚 What I Learned: Understanding the properties of a complete binary tree. Using BFS to validate structural constraints. Handling null conditions carefully during traversal. Strengthening queue-based tree problem-solving. Building strong fundamentals in tree structures Consistency is key to mastering DSA #LeetCode #DSA #BinaryTree #CompleteBinaryTree #BFS #Queue #Java #CodingJourney #ProblemSolving #100DaysOfCode #TechGrowth
To view or add a comment, sign in
-
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