#100DaysOfCode – Day 66 String Manipulation & Primitive Decomposition 🧩 Task: Given a valid parentheses string, decompose it into its primitive components and then remove the outermost parentheses from each component. Example: Input: s = "(()())(())" Primitive Decomposition: "(()())" + "(())" After removing outermost parentheses: "()()" + "()" Output: "()()()" My Approach: I iterated through the string while keeping a counter to track the balance of open parentheses. When an opening parenthesis ( was found, I incremented the counter. If the count was greater than 1, it meant this parenthesis was not an outermost one, so I appended it to the result. When a closing parenthesis ) was found, I only appended it if the counter was greater than 1 before decrementing. This ensures the final closing parenthesis of a primitive part is excluded. This simple counter-based approach effectively identifies and removes the correct parentheses without needing a more complex data structure like a stack. Time Complexity: O(N) Space Complexity: O(N) Sometimes, a simple counter is all you need to elegantly handle nested structures. It can be a clean and efficient alternative to more complex data structures for certain problems. #takeUforward #100DaysOfCode #Java #ProblemSolving #LeetCode #DataStructures #Algorithms #StringManipulation #CodeNewbie
Decomposing Parentheses with a Simple Counter
More Relevant Posts
-
✅Day 40 : Leetcode 81 - Search in Rotated Sorted Array - 2 #60DayOfLeetcodeChallenge 🧩 Problem Statement You are given an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]. Given the array nums after rotation and an integer target, return true if target is present in nums, otherwise return false. You must reduce the number of overall operations as much as possible. 💡 My Approach Use a modified binary search since the array is rotated. Initialize low = 0 and high = n - 1. While low <= high: Compute mid = low + (high - low) / 2. If nums[mid] == target, return true. If nums[low] == nums[mid] && nums[mid] == nums[high], increment low and decrement high to skip duplicates. If the left half is sorted (nums[low] <= nums[mid]): Check if target lies in this range; if yes, move high = mid - 1, else move low = mid + 1. Else, the right half is sorted: If target lies in this range, move low = mid + 1, else move high = mid - 1. If no match is found, return false. ⏱️ Time Complexity Average Case: O(log n) Worst Case (due to duplicates): O(n) #BinarySearch #LeetCode #Array #Rotation #Java #CodingPractice #DataStructures
To view or add a comment, sign in
-
-
💻 Day 63 of #LeetCode100DaysChallenge Solved LeetCode 290: Word Pattern — a great problem for strengthening hash mapping and bijection logic between characters and words. 🧩 Problem: Given a pattern and a string s, determine if s follows the same pattern. Each letter in the pattern maps to exactly one unique word in s, and each unique word in s maps to exactly one letter in the pattern. No two letters map to the same word, and no two words map to the same letter. 💡 Approach — HashMap + Set: 1️⃣ Split s into words. If pattern length ≠ word count, return false. 2️⃣ Use two data structures: A HashMap<Character, String> to map pattern → word. A HashSet<String> to track if a word is already mapped. 3️⃣ Iterate through both: If the character was seen before, check if it maps to the same word. If it’s new, ensure the word isn’t already mapped to another letter. 4️⃣ Return true if all pairs match consistently. ⚙️ Complexity: Time: O(N) — one pass through all words. Space: O(N) — for the map and set. ✨ Key Takeaways: ✅ Strengthened understanding of bijections and hash-based pattern matching. ✅ Improved clarity on how to manage two-way mapping between characters and strings. ✅ Practiced clean iteration and map validation logic — crucial for real-world parsing and pattern-matching problems. #LeetCode #100DaysOfCode #Java #HashMap #PatternMatching #DSA #ProblemSolving #WomenInTech #CodingChallenge
To view or add a comment, sign in
-
-
🚀 Day 28 of #100DaysOfCode Today’s challenge was all about understanding frequency patterns in arrays — a simple yet powerful concept in hashing 🔍 LeetCode 1207 – Unique Number of Occurrences 🔢 📌 Problem Summary: Given an integer array, determine whether each value appears a unique number of times. In other words, 👉 No two numbers should share the same frequency. 💡 Example: Input: [1,2,2,1,1,3] Output: true Because frequencies are: 1 → 3 times 2 → 2 times 3 → 1 time All unique ✔️ 🧠 My Approach: I solved it using a combination of HashMap + HashSet: 1️⃣ Count the occurrences of each number using a HashMap. 2️⃣ Insert all frequency values into a HashSet. 3️⃣ If the size of the HashSet equals the size of the map → all frequencies are unique ✔️ 4️⃣ Otherwise → duplicates exist ❌ A clean and efficient hashing technique. ⚙️ Complexity: Time: O(n) ⏱️ Space: O(n) 💾 (storing frequencies) 💡 Key Learning: HashMaps aren’t just for storing counts—they can reveal patterns, validations, and uniqueness constraints when combined with sets. This problem reinforced how frequency-based logic solves many real-world scenarios like: ✔ Detecting duplicates ✔ Comparing patterns ✔ Character/string analysis ✔ Data validation 🔥 Result: Code ran successfully with 0 ms Runtime, accepted on the first attempt! Small challenge, clean logic, satisfying finish 💪 On to the next one! 🚀 #100DaysOfCode #LeetCode #HashTable #Java #ProblemSolving #DSA #CodingJourney
To view or add a comment, sign in
-
-
💡 LeetCode 1528 – Shuffle String 💡 Today, I solved LeetCode Problem #1528: Shuffle String, which tests how well you can handle index mapping and string reconstruction in Java — an elegant exercise in array manipulation and string handling. ✨ 🧩 Problem Overview: You’re given a string s and an integer array indices. Each character at position i in s must be moved to position indices[i] in the new string. Return the final shuffled string. 👉 Example: Input → s = "codeleet", indices = [4,5,6,7,0,2,1,3] Output → "leetcode" 💡 Approach: 1️⃣ Create a char array of the same length as s. 2️⃣ Loop through each character in s, placing it at the position specified by indices[i]. 3️⃣ Convert the filled character array back to a string. ⚙️ Complexity Analysis: ✅ Time Complexity: O(n) — Single pass through the string. ✅ Space Complexity: O(n) — For the result character array. ✨ Key Takeaways: Reinforced understanding of index mapping between arrays and strings. Practiced how to reconstruct a string efficiently without using extra data structures. A great example of how simple iteration can solve structured reordering problems cleanly. 🌱 Reflection: Sometimes, challenges like this remind us that not every problem requires a complex algorithm — precision, clarity, and clean mapping logic often do the job best. Staying consistent with such problems builds both confidence and coding discipline. 🚀 #LeetCode #1528 #Java #StringManipulation #ArrayMapping #DSA #ProblemSolving #CleanCode #CodingJourney #AlgorithmicThinking #ConsistencyIsKey
To view or add a comment, sign in
-
-
📅 Day 90 of #100DaysOfLeetCode Problem: Smallest String Starting From Leaf (LeetCode #988) Approach: We are given a binary tree where each node stores a value from 0 to 25, representing letters 'a' to 'z'. We must form strings from leaf → root and return the lexicographically smallest one. To solve this: ✅ Use DFS to explore all paths ✅ Convert node values to characters ✅ Build strings from bottom to top ✅ Track the minimum lexicographical string Key Idea: Perform a DFS traversal and store the path characters. Whenever we reach a leaf, reverse the current path (leaf → root order), form a string, and compare it with the current smallest string. Steps: DFS from root to all leaves Maintain list of path characters When at leaf → form & compare the string Return the smallest lexicographical string found Complexity: ⏱️ Time: O(n × h) — exploring all paths & string creation 💾 Space: O(h) — recursion stack & path storage where h = height of tree 🔗 Problem Link: https://lnkd.in/dyuMJ8QK 🔗 Solution Link: https://lnkd.in/d8hgy4N8 #LeetCode #100DaysOfCode #BinaryTree #DFS #TreeTraversal #StringProblems #LexicographicalOrder #DataStructures #Java #Algorithms #ProblemSolving #DailyCoding #CodingChallenge #BuildInPublic #SoftwareEngineering #LearnToCode
To view or add a comment, sign in
-
-
👉 LeetCode 367: Valid Perfect Square. Binary search problem - this time to check if a number is a perfect square without using any built-in square root function. 👇 Here’s my implementation: class Solution { public boolean isPerfectSquare(int num) { if(num == 1){ return true; } int left = 1, right = num/2; while(left<=right){ int mid = left + (right-left)/2; if(mid == num/mid && num%mid == 0){ return true; }else if(mid < num/mid){ left = mid + 1; }else{ right = mid - 1; } } return false; } } 👉 Step-by-step logic: 1. Handle the edge case when num is 1. 2. Use binary search between 1 and num/2. 3. Calculate mid, then check if mid * mid == num. .To avoid overflow, the code uses num/mid instead of mid * mid. 4. If it matches perfectly and num % mid == 0, return true. 5. Adjust search boundaries accordingly until you find it or exhaust all options. 👉 Time Complexity:O(log n) — binary search halves the range each time. 👉 Space Complexity:O(1) — only a few integer variables are used. #LeetCode #Java #ProblemSolving #BinarySearch #Coding
To view or add a comment, sign in
-
🚩 Problem: 239. Sliding Window Maximum 🔥 Day 51 of #100DaysOfLeetCode 🔍 Problem Summary: Given an integer array nums and an integer k, return an array containing the maximum value in every sliding window of size k. This is a classic sliding window problem that looks heavy, but with the right data structure, the solution is clean and O(n). 🧠 Intuition: A normal approach checks each window → O(n × k) (too slow). Instead, use a Deque to store indices of useful elements: The deque always keeps elements in decreasing order. The front of the deque is always the maximum of the current window. Remove elements: Outside the current window Smaller than the new incoming element This gives us the maximum in O(1) per window ⇒ total O(n). ⚙️ Performance: ⏱️ Runtime: 28 ms 🚀 💪 Beats: 98.7% of Java solutions 💾 Memory: 63 MB ⚡ (Beats ~96% of users) 📊 Complexity: Time Complexity: O(n) Space Complexity: O(k) ✨ Key Takeaway: The Deque technique is one of the most powerful sliding window optimizations — turning a potentially quadratic problem into linear time with a clean and elegant solution. Link:[https://lnkd.in/gJTzhcR2] #100DaysOfLeetCode #Day51 #Problem239 #SlidingWindowMaximum #Deque #SlidingWindow #Algorithms #DSA #Java #CodingChallenge #ProblemSolving #LeetCode #InterviewPreparation #CrackingTheCodingInterview #SoftwareEngineering #DataStructures #CodingCommunity #ArjunInfoSolution #CodeNewbie #Programming #TechCareers #CareerGrowth #ZeroToHero #LearnToCode #CodingIsFun #ComputerScience #JavaDeveloper #DeveloperJourney #AI #MachineLearning #UnityGameDev #GameDeveloper
To view or add a comment, sign in
-
-
✅Day 42 : Leetcode 154 - Find Minimum in Rotated Sorted Array-2 #60DayOfLeetcodeChallenge 🧩 Problem Statement You are given an array nums that is sorted in ascending order and then rotated between 1 and n times. The array may contain duplicates. Your task is to find and return the minimum element in the rotated sorted array. You must minimize the number of overall operations as much as possible. 💡 My Approach I used a modified binary search technique to handle both rotation and duplicates. Initialize two pointers — low = 0 and high = n - 1. Calculate the middle index mid = low + (high - low) / 2. Update the answer as ans = min(ans, nums[mid]). If nums[low] == nums[mid] && nums[mid] == nums[high], move both low++ and high-- to skip duplicates. If the left half is sorted (nums[low] <= nums[mid]), update the answer and move to the right half (low = mid + 1). Otherwise, move to the left half (high = mid - 1). Continue until low > high. This efficiently finds the minimum even when duplicates exist. ⏱️ Time Complexity Worst Case: O(n) — when many duplicates exist. Average Case: O(log n) — behaves like binary search when duplicates are few. #BinarySearch #LeetCode #RotatedArray #Java #DSA #ProblemSolving #CodingPractice #LeetCodeHard
To view or add a comment, sign in
-
-
✅ Day 68 of LeetCode Medium/Hard Edition Today’s challenge was “Number of Ways to Form a Target String Given a Dictionary” — a brilliant Dynamic Programming and Combinatorics problem that tests precision in transitions and precomputation logic 🧩⚙️ 📦 Problem: You’re given an array of equal-length strings words and a target string target. You must form target from left to right by picking characters from the columns of words under these rules: 1️⃣ Once you use column k from any word, all columns ≤ k in every word become unusable. 2️⃣ You can use multiple characters from the same word, respecting column progression. Return the number of ways to form target modulo 1e9 + 7. 🔗 Problem Link: https://lnkd.in/gns9CwWa ✅ My Submission: https://lnkd.in/g7bsgZq9 💡 Thought Process: This problem is a clever mix of frequency compression and DP memoization. We precompute a frequency table freq[26][m], where each cell represents how many words contain a given letter at column m. Then, using recursion with memoization: 🎯 At each step (i, j) Either use freq[target[i]][j] if it exists → multiply by ways for the next position (i+1, j+1) Or skip the current column → move to (i, j+1) The recurrence relation: dp[i][j] = freq[target[i]][j] * dp[i+1][j+1] + dp[i][j+1] All computations are done modulo 1e9 + 7. ⚙️ Complexity: ⏱ Time: O(26 * n + t * m) — efficient due to frequency precomputation 💾 Space: O(t * m) — for memoized DP table 💭 Takeaway: This challenge reinforced how precomputation and state optimization can transform a seemingly exponential recursion into an elegant polynomial-time solution 🚀 #LeetCodeMediumHardEdition #100DaysChallenge #DynamicProgramming #Combinatorics #ProblemSolving #Java #CodingChallenge #DSA
To view or add a comment, sign in
-
-
#Day_34 Today’s problem was a satisfying one to solve — “Single Element in a Sorted Array” 🔍 Given a sorted array where every element appears twice except for one unique element, the task is to identify that single element. At first, it seems like a simple linear scan could do the job — and yes, it can. But I focused on building a clean and logical O(n) approach before thinking about optimization 🧠 Approach We observe that: Every element appears in pairs, and because the array is sorted, duplicates are adjacent. The unique element is the only one that doesn’t match its left or right neighbor. We can handle three cases: First element: If it’s not equal to the next one → it’s the single element. Last element: If it’s not equal to the previous one → it’s the single element. Middle elements: If an element is different from both its previous and next → that’s our answer. This way, we can detect the single element in just one pass through the array ⏱ Complexity Time: O(n) — We traverse the array once. Space: O(1) — No extra memory used. 💬 Reflection This problem is a good reminder that not every efficient solution has to start complex. Sometimes, the cleanest brute-force version gives a perfect foundation for further optimization — in this case, even leading to an O(log n) binary search variant. Each problem in this challenge pushes me to think deeper about patterns, structure, and clarity in problem-solving. #CodingJourney #LeetCode #ProblemSolving #100DaysOfCode #Java #LearnByDoing #DSA
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