Day - 73 Valid Parentheses The problem - Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. A string is valid if: open brackets are closed by the same type of brackets, open brackets are closed in the correct order, and every close bracket has a corresponding open bracket. Brute Force - Repeatedly scan the string and remove valid pairs like "()", "{}", "[]" until no more pairs can be removed. If the string becomes empty, it's valid. This gives O(n²) time complexity due to multiple passes and string manipulation. Approach Used - •) Create a Stack<Character> to track opening brackets •) Create a HashMap<Character, Character> to map closing to opening brackets, ')' → '(' , '}' → '{' and ']' → ‘[‘. •) Process each character, Iterate through each character c in the string, 1 - If c is an opening bracket, push it onto the stack. 2 - If c is a closing bracket, - Check if stack is empty, return false. - Pop from stack and check if it matches mapping.get(c), if mismatch → return false. •) Final Validation, 1 - After processing all characters, check if stack is empty. 2 - Empty stack means all brackets matched correctly. 3 - Non-empty stack means unmatched opening brackets remain. Complexity - Time - O(n), single pass through the string, each character processed once and stack operations (push/pop) are O(1). Space - O(n), stack can hold up to n/2 opening brackets in worst case. Note - Stack naturally handles nested structures with LIFO (Last-In-First-Out) behavior. Each closing bracket must match the most recent unmatched opening bracket. HashMap enables O(1) lookup for matching pairs, making validation efficient. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
Validating Brackets with Stack and HashMap
More Relevant Posts
-
🚀 Day 38 of #100DaysOfCode Solved 154. Find Minimum in Rotated Sorted Array II on LeetCode 🔍 🧠 Key Insight: The array is sorted but rotated, and this version introduces duplicates, which makes the binary search logic slightly trickier. ⚙️ Approach: 🔹Use binary search with left and right pointers 🔹Compare nums[mid] with nums[right]: 🔹If nums[mid] > nums[right] → minimum lies in the right half 🔹If nums[mid] < nums[right] → minimum lies in the left half (including mid) 🔹If equal → safely shrink the search space by decrementing right This handles the ambiguity caused by duplicates. ⏱️ Time Complexity: Average: O(log n) Worst case: O(n) (when many duplicates exist) 📦 Space Complexity: O(1) #100DaysOfCode #LeetCode #DSA #BinarySearch #Arrays #Java #ProblemSolving #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟑𝟑 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on generating all unique subsets when the array contains duplicate elements. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Subsets II 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 • First, sorted the array to group duplicate elements together • Used backtracking to explore subset possibilities • At each step, two choices exist: include the element or skip it • When skipping, moved forward past duplicate elements to avoid repeated subsets This ensures unique subsets are generated. 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • Sorting helps handle duplicates effectively • Backtracking explores all combinations systematically • Skipping duplicate elements prevents repeated subsets • Understanding recursion trees helps visualize subset generation 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Time: O(n × 2ⁿ) • Space: O(n) (recursion stack) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 When duplicates exist, generating combinations isn’t the challenge — avoiding repeated ones is. 33 days consistent 🚀 On to Day 34. #DSA #Arrays #Backtracking #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
🔥 Day 98 of #100DaysOfCode Today’s challenge: LeetCode – Search in Rotated Sorted Array II 🔄🔍 📌 Problem Summary You are given a rotated sorted array that may contain duplicates. Your task is to determine whether a target exists in the array. Example: Input: nums = [2,5,6,0,0,1,2], target = 0 Output: true 🧠 Approach Used: Linear Search In this implementation, we simply iterate through the array and check if the element matches the target. ⚙️ Logic for(int i = 0; i < nums.length; i++){ if(nums[i] == target){ return true; } } return false; 💡 Explanation Traverse the array from start to end If the target is found → return true If the loop finishes → return false ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) 🚀 Performance Runtime: 0 ms Memory: 44.9 MB 🧠 Learning This problem is a variation of Search in Rotated Sorted Array, but with duplicates allowed. While a Binary Search solution exists, duplicates can break the strict ordering and make the logic more complex. A simple linear scan ensures correctness in all cases. Only 2 days left to complete #100DaysOfCode 🚀 Almost at the finish line! On to Day 99 🔥 #100DaysOfCode #LeetCode #Java #DSA #CodingJourney #InterviewPrep
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟐𝟓 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on sorting an array containing only three distinct values using an efficient counting approach. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Sort Colors 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 𝟏 – 𝐂𝐨𝐮𝐧𝐭𝐢𝐧𝐠 𝐀𝐫𝐫𝐚𝐲 • Created a count array of size 3 • Counted occurrences of 0, 1, and 2 • Overwrote the original array using the frequency values • Simple and easy to implement 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • When value range is small, counting is powerful • Rewriting the array can be simpler than swapping • Constraints often guide the optimal approach • Clear thinking avoids overcomplication 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Time: O(n) • Space: O(1) (since count array size is constant) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Not every sorting problem needs full sorting logic — sometimes counting is enough. 25 days consistent. On to Day 26 🚀 #DSA #Arrays #Sorting #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
After exploring path-based recursion, I moved to generating all subsets of a string. This introduced a very clean pattern - For every element, you either include it or exclude it. That’s it. But that “either-or” creates a full decision tree. What became clear here: - Every element creates two branches. - Total subsets = 2ⁿ (tree expansion becomes visible). - Recursion can systematically explore combinations. - The structure is more important than the syntax. Core logic : if (index == str.length()) { System.out.println(current); return; } subset(index + 1, current + str.charAt(index)); // include subset(index + 1, current); // exclude This is where recursion started feeling predictable. Once the pattern is seen, similar problems start looking connected. #recursion #java #dsajourney #backtracking #problemSolving
To view or add a comment, sign in
-
Day 49 Problem statement: You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers. The test cases are generated so that the answer fits in a 32-bits integer Example: For the tree [1,0,1,0,1,0,1] Paths formed: 100 → 4 101 → 5 110 → 6 111 → 7 Total = 22 Approach: While traversing the tree using DFS, we build the binary number step by step. At each node: val = 2 * val + root.val Why multiply by 2? Because in binary: Left shift = multiply by 2 Then add current bit This simulates constructing a binary number as we move down the tree. Approach: Use DFS (Preorder traversal) Carry the current binary value When we reach a leaf → return the computed number Sum left and right subtree results Java code class Solution { public int dfs(TreeNode root, int val){ if(root == null) return 0; val = 2 * val + root.val; if(root.left == null && root.right == null){ return val; } return dfs(root.left, val) + dfs(root.right, val); } public int sumRootToLeaf(TreeNode root) { return dfs(root, 0); } } #HappyCoding #DSA #Trees #LeetCode #DSA #BinaryTree #Algorithms #Java #ProblemSolving #CodingJourney #InterviewPreparation #SoftwareEngineering #CareerGrowth
To view or add a comment, sign in
-
Day - 75 Next Greater Element I The problem - Given two arrays nums1 and nums2 where nums1 is a subset of nums2, for each element in nums1, find the next greater element in nums2. The next greater element is the first greater element to the right. If it doesn't exist, return -1. Brute Force - For each element in nums1, find its position in nums2, then scan right to find the first greater element. This gives O(n × m) time complexity where n = length of nums1 and m = length of nums2. Approach Used - •) Create array nextGreater[10001] to store next greater element for each number and a Stack<Integer> for tracking elements. •) Traverse nums2 from right to left (i = length-1 to 0), 1 - While stack is not empty && stack.peek() ≤ nums2[i], pop from stack. 2 - If stack is empty, nextGreater[nums2[i]] = -1, else nextGreater[nums2[i]] = stack.peek(). 3 - Push nums2[i] onto stack. •) For each element in nums1, replace it with nextGreater[nums1[i]], return nums1. Complexity - Time - O(n + m) where n = nums1.length, m = nums2.length. Space - O(m), for stack and nextGreater array. Note - Using a monotonic decreasing stack while traversing right to left allows us to efficiently find the next greater element. Elements smaller than current are popped (they can't be next greater for anyone), and the remaining top element is the answer. The array acts as a lookup table for O(1) retrieval. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
Day 8/60 – LeetCode Challenge 🔥 Problem: Longest Substring Without Repeating Characters Today’s concept: Sliding Window + HashMap 💡 The question is: Given a string s, find the length of the longest substring without repeating characters. Brute force approach? Generate all substrings and check duplicates → O(n²) ❌ Better approach? Use Sliding Window with a HashMap. Intuition (Based on My Code): I used two pointers: • low → start of the window • high → end of the window As high moves forward: • I add the character to the HashMap • The map stores character frequency Now here’s the important observation: If there are no duplicates in the current window, then: map.size() == window length But if a duplicate exists, then: map.size() < window length So while map.size() < (high - low + 1), I shrink the window by: • Reducing frequency of s.charAt(low) • Removing it from map if frequency becomes 0 • Moving low forward After the window becomes valid again, I update the result with: res = max(res, current window length) Why this works? Because: • Each character enters the window once • Each character leaves the window once So the total complexity stays linear. Time Complexity: O(n) Space Complexity: O(n) Key Learning: When the question involves: • Longest substring • No repeating characters • Continuous segment Think → Sliding Window + Hashing Day 8 completed ✅ Consistency continues 🚀 #LeetCode #DSA #SlidingWindow #HashMap #Java #CodingChallenge #PlacementPreparation
To view or add a comment, sign in
-
-
Day 58/100 – LeetCode Challenge ✅ Problem: Longest Balanced Substring II Difficulty: Medium Language: Java Approach: Multiple Pattern Detection + Prefix Difference Mapping Time Complexity: O(n) Space Complexity: O(n) Key Insight: Balanced substrings must have equal counts of characters in three possible patterns: Single character run - consecutive same characters Two characters - equal occurrences of two specific chars Three characters - all three chars appear same number of times Solution Brief: countOne(): Track longest consecutive run of same character. countTwo(): For two chars (like 'a'/'b'), use prefix sum where n1=+1, n2=-1; reset on other chars. countThree(): Track differences (a-b) and (a-c) as state; when same state repeats, balanced substring found. #LeetCode #Day58 #100DaysOfCode #String #HashMap #Java #Algorithm #CodingChallenge #ProblemSolving #LongestBalancedSubstringII #HardProblem #PrefixSum #StateTracking #DSA
To view or add a comment, sign in
-
-
Day 12/30 – Search in Rotated Sorted Array 🚀 Core Idea: Even in a rotated array, one half is always sorted. Strategy: • Apply Binary Search • Identify the sorted half • Check if target lies inside it • Narrow the search space Complexity: Time → O(log n) Space → O(1) Binary Search with a twist 🔥 #30DaysOfCode #Java #BinarySearch #DSA #InterviewPrep
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