🌟 Day 26 of #100DaysOfCode 🌟 🔍 Remove Duplicate Letters — Lexicographically Smallest Unique String 🔹 What I Solved Today, I tackled the “Remove Duplicate Letters” problem — a fascinating challenge that combines stack operations, greedy logic, and lexicographical ordering. It’s a perfect test of both analytical and implementation skills. 📝 Problem Statement Given a string s, remove duplicate letters so that every letter appears once and only once. You must ensure the resulting string is the smallest in lexicographical order among all possible results. ✅ Example 1: Input: s = "bcabc" Output: "abc" ✅ Example 2: Input: s = "cbacdcbc" Output: "acdb" Constraints: 1 ≤ s.length ≤ 10⁴ s consists of lowercase English letters 🧠 Concepts Used Stack Greedy Algorithm HashMap / Frequency Counting Character Visitation Tracking ⚙️ Approach Count the frequency of each character using a map. Use a stack to build the result string. Iterate through each character: Decrease its frequency (as it’s now visited). If the character is already in the stack, skip it. Otherwise, while the current character is smaller than the top of the stack and the top of the stack will appear later again, pop it out to maintain lexicographical order. Push the current character into the stack. Convert the stack to the final result string. 🚀 What I Learned This problem beautifully demonstrates how greedy thinking and data structures like stacks can work together to maintain order and constraints. It deepened my understanding of how lexicographical optimization problems can be efficiently solved using character frequency and conditional popping. #100DaysOfCode #ProblemSolving #Java #DataStructures #Algorithms #CodingJourney #GeeksforGeeks #KeepLearning
Solved "Remove Duplicate Letters" with Stack and Greedy Algorithm
More Relevant Posts
-
🚀 Day 60 of #100DaysOfCode 🚀 Today, I solved LeetCode Problem #137 – Single Number II 🧩 📘 Problem Statement: Given an integer array where every element appears three times except for one that appears exactly once, find that single element and return it. The challenge: solve it with O(n) time and O(1) space complexity. 💻 Language: Java ⚡ Runtime: 0 ms — Beats 100.00% 📉 Memory: 45.54 MB — Beats 56.30% 🧠 Concept Used: 🔹 Bit Manipulation — A powerful yet tricky technique that leverages binary operations to track occurrences of bits efficiently. 🔹 Instead of using extra space or hash maps, we track bits that appear once and twice using two integer variables: ✅ once → bits that appeared once ✅ twice → bits that appeared twice The trick lies in updating them using XOR (^) and NOT (~) to "cancel out" bits appearing three times. 🧩 Approach Summary: 1️⃣ Initialize two variables once = 0 and twice = 0. 2️⃣ For every number in the array: - Update once and twice based on how many times a bit has appeared. 3️⃣ After processing all numbers, once holds the value of the single element. ✅ Complexity: Time: O(n) Space: O(1) ✨ Takeaway: This problem teaches how bitwise logic can replace traditional data structures, achieving the same result with constant space — a crucial optimization in system-level programming and interviews. #100DaysOfCode #LeetCode #Java #BitManipulation #ProblemSolving #CleanCode #DataStructures #Algorithms #TechLearning #CodingChallenge #SoftwareEngineering #InterviewPreparation
To view or add a comment, sign in
-
-
🚀 Day 58 of #100DaysOfCode 🚀 Today, I solved LeetCode Problem #852 – Peak Index in a Mountain Array 🏔️ 📘 Problem Statement: Given an integer array that first increases and then decreases (a “mountain array”), find the index of the peak element — the point where the sequence changes from increasing to decreasing. 💻 Language: Java ⚡ Runtime: 0 ms — Beats 100.00% ⚡ 📉 Memory: 56.29 MB — Beats 60.76% 🧠 Concept Used: 🔹 Binary Search Optimization – Instead of linearly scanning the array, I applied binary search to achieve O(log n) time complexity. 🔹 This approach identifies the peak by checking midpoints and adjusting the search range efficiently. 🧩 Approach: 1️⃣ Initialize low = 0 and high = arr.length - 1. 2️⃣ Use binary search: ➡️ If arr[mid] < arr[mid + 1], the peak lies to the right → move low = mid + 1. ➡️ Else, the peak is at mid or to the left → move high = mid. 3️⃣ Return low when low == high — the index of the peak. ✅ Complexity: Time: O(log n) Space: O(1) ✨ Takeaway: Binary Search isn’t just for finding numbers — it’s a pattern for optimizing any “search in sorted behavior” scenario. Learning to spot monotonic trends in problems can turn O(n) solutions into O(log n) ones! #100DaysOfCode #LeetCode #Java #ProblemSolving #Algorithms #BinarySearch #DataStructures #CodingChallenge #CleanCode #SoftwareEngineering #TechLearning
To view or add a comment, sign in
-
-
🚩 Problem: 78. Subsets 🔥 Day 56 of #100DaysOfLeetCode 🔍 Problem Summary: Given an integer array nums, return all possible subsets (the power set). The solution set must not contain duplicates, and the order does not matter. 🧠 Intuition: This is one of the simplest and cleanest backtracking problems. At each index, you have only two choices: Include the current element Exclude the current element This naturally builds the entire power set. Alternatively, you can also build subsets by expanding a list from left to right. ✅ Backtracking Approach: Start with an empty subset Recursively explore adding each number After each choice, backtrack and remove it Add all generated combinations into the result Super clean and beginner-friendly. ⚙️ Performance: ⏱️ Runtime: 1 ms 🚀 💪 Beats: 97% of Java solutions 💾 Memory: 43 MB ⚡ (Beats ~90% of users) 📊 Complexity: Time Complexity: O(n × 2ᶰ) Space Complexity: O(n) (recursion + temp list) ✨ Key Takeaway: This problem teaches the classic recursive structure used for: Subsets Combinations Nested choices Decision-tree exploration It's the perfect stepping stone to more advanced backtracking problems. Link:[https://lnkd.in/gfQV_8w4] #100DaysOfLeetCode #Day56 #Problem78 #Subsets #Backtracking #Recursion #Algorithms #DSA #Java #ProblemSolving #LeetCode #CodingChallenge #CodingCommunity #InterviewPreparation #CrackingTheCodingInterview #SoftwareEngineering #DataStructures #ArjunInfoSolution #DeveloperJourney #LearnToCode #TechCareers #CareerGrowth #CodeNewbie #ZeroToHero #CodingIsFun #JavaDeveloper #GameDeveloper #Unity #AI #MachineLearning
To view or add a comment, sign in
-
-
🚩 Problem: 560. Subarray Sum Equals K 🔥 Day 45 of #100DaysOfLeetCode 🔍 Problem Summary: Given an integer array nums and an integer k, return the total number of continuous subarrays whose sum equals k. 🧠 Intuition: A naive solution checks every subarray (O(n²)), but we can do better using Prefix Sums + HashMap. We keep track of all prefix sums and how many times each sum occurs. For each element: Compute current prefix sum. Check if (prefixSum - k) exists in the map — it means there’s a subarray that adds up to k. Add the frequency of (prefixSum - k) to the count. ✅ Optimized Approach (Prefix Sum + HashMap): Initialize a HashMap with {0 : 1} to handle subarrays starting from index 0. Maintain sum and count. Traverse through array, updating prefix sum and checking (sum - k) in map. 📊 Complexity: Time Complexity: O(n) Space Complexity: O(n) ✨ Key Takeaway: This problem beautifully demonstrates how prefix sums + hash maps transform a brute-force O(n²) approach into an elegant O(n) solution. A must-know technique for interviews and real-world data stream problems. Link:[https://lnkd.in/g-cv3M96] #100DaysOfLeetCode #Day45 #Problem560 #SubarraySumEqualsK #PrefixSum #HashMap #Java #Algorithms #DSA #LeetCode #ProblemSolving #CodingChallenge #CodingCommunity #InterviewPreparation #CrackingTheCodingInterview #DataStructures #SoftwareEngineering #CodeNewbie #DeveloperJourney #ArjunInfoSolution #Programming #LearnToCode #TechCareers #CareerGrowth #ComputerScience #ZeroToHero #CodeLife #CodingIsFun #GeeksForGeeks #CodeEveryday #GameDeveloper #Unity #JavaDeveloper #AI #MachineLearning
To view or add a comment, sign in
-
-
🚀 Day 52 of #100DaysOfCode 🚀 Today I solved LeetCode Problem #389 – Find the Difference 🧩 This problem is a great example of using ASCII value manipulation to solve what seems like a string comparison challenge. 💡 Key Learnings: Strengthened understanding of character encoding (ASCII values) and how they can simplify logic. Learned how summing character values can help detect differences efficiently without extra data structures. Reinforced the value of O(n) solutions for string-based problems. 💻 Language: Java ⚡ Runtime: 1 ms — Beats 99.32% 🚀 📉 Memory: 41.9 MB — Beats 65.84% 🧠 Approach: 1️⃣ Convert both strings to character arrays. 2️⃣ Compute the sum of ASCII values of both. 3️⃣ The difference between sums gives the ASCII value of the extra character in t. Simple, elegant, and efficient! ⚙️ Sometimes, a clever use of ASCII arithmetic can replace complex logic — efficiency lies in simplicity. #100DaysOfCode #LeetCode #Java #ProblemSolving #CodingChallenge #Algorithms #DataStructures #SoftwareDevelopment #LearningEveryday #CleanCode
To view or add a comment, sign in
-
-
🌟 Day 25 of #100DaysOfCode 🌟 🔍 Equal Character Frequency — Checking if All Characters Occur Equally 🔹 What I Solved Today, I solved the “Check if All Characters Have Equal Occurrences” problem — a simple yet insightful exercise in string manipulation and frequency analysis. 📝 Problem Statement Given a string s, return true if all characters that appear in s have the same number of occurrences. Otherwise, return false. ✅ Example 1: Input: s = "abacbc" Output: true Explanation: All characters ('a', 'b', 'c') occur twice. ✅ Example 2: Input: s = "aaabb" Output: false Explanation: 'a' appears 3 times, 'b' appears 2 times. Constraints: 1 ≤ s.length ≤ 1000 s consists of lowercase English letters. 🧠 Concepts Used Frequency Counting Array Manipulation Conditional Checking ⚙️ Approach Create an integer array of size 26 to store character counts. Count the frequency of each character. Identify the first non-zero frequency. Verify that all other non-zero frequencies match this one. Return true if all are equal, otherwise false. 🚀 What I Learned This problem reminded me that even simple problems can sharpen logical reasoning. Understanding how to work with frequency maps and character arrays is crucial for tackling many string-related challenges efficiently. Feeling great to be back in rhythm and pushing forward in my #100DaysOfCode journey! #100DaysOfCode #ProblemSolving #Java #DataStructures #Algorithms #CodingJourney
To view or add a comment, sign in
-
-
🌟 Day 28 of #100DaysOfCode 🌟 🔍 Reverse Words in a String — Clean & Elegant String Manipulation 🔹 What I Solved Today, I solved the classic “Reverse Words in a String” problem — a deceptively simple challenge that tests your understanding of string manipulation, trimming spaces, and efficient iteration. This problem is all about cleaning messy input and reordering data logically, which is a valuable skill in real-world text processing tasks. 📝 Problem Statement Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The returned string should have only a single space separating words — with no leading or trailing spaces. Example 1: Input: s = "the sky is blue" Output: blue is sky the Example 2: Input: s = " hello world " Output: world hello Example 3: Input: s = "a good example" Output: example good a 🧠 Concepts Used String Splitting & Trimming Whitespace Handling Iteration & StringBuilder Efficient Memory Management ⚙️ Approach 1️⃣ Trim the string to remove extra leading/trailing spaces. 2️⃣ Split the string by one or more spaces using regex (\\s+). 3️⃣ Iterate backward through the words array. 4️⃣ Append words to a StringBuilder, adding spaces only between words. 5️⃣ Return the final reversed and clean string. 🚀 What I Learned This problem reinforced how attention to detail matters in coding — especially when handling strings and whitespace. It also reminded me that even simple problems can teach clean code principles, edge case thinking, and time-space optimization. Grateful to K.R. Mangalam University for continuously motivating me on this journey of learning and consistency. #100DaysOfCode #Java #ProblemSolving #CodingJourney #DataStructures #Algorithms
To view or add a comment, sign in
-
-
🚩 Problem: 347. Top K Frequent Elements 🔥 Day 48 of #100DaysOfLeetCode 🔍 Problem Summary: Given an integer array nums and an integer k, return the k most frequent elements. You must solve this in better than O(n log n) time complexity. 🧠 Intuition: We count how often each number appears using a HashMap, then use Bucket Sort (or a Max-Heap) to efficiently extract the most frequent numbers. This avoids sorting all elements and achieves O(n) performance. ✅ Optimized Approach (HashMap + Bucket Sort): Count frequency of each element. Group elements by frequency using buckets. Traverse buckets from highest to lowest frequency to collect the top k elements. ⚙️ Performance: ⏱️ Runtime: 4 ms 🚀 💪 Beats: 98.72% of Java solutions 💾 Memory: 46.2 MB ⚡ (Beats 93.10% of users) 📊 Complexity: Time Complexity: O(n) Space Complexity: O(n) ✨ Key Takeaway: This problem reinforces how frequency mapping + bucket sorting can optimize data ranking problems to O(n). A must-know pattern for data analysis, system design, and interviews. LINK:[https://lnkd.in/gTts2ehN] #100DaysOfLeetCode #Day48 #Problem347 #TopKFrequentElements #HashMap #BucketSort #PriorityQueue #Java #Algorithms #DSA #ProblemSolving #LeetCode #CodingChallenge #CodingCommunity #InterviewPreparation #CrackingTheCodingInterview #DataStructures #SoftwareEngineering #DeveloperJourney #ArjunInfoSolution #CodeNewbie #Programming #LearnToCode #TechCareers #CareerGrowth #ZeroToHero #CodeEveryday #CodeLife #CodingIsFun #ComputerScience #GeeksForGeeks #GameDeveloper #Unity #JavaDeveloper #AI #MachineLearning
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
-
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