Removing Duplicate Letters in Lexicographical Order

✳️Day 23 of #100DaysOfCode✳️ 🚀Solved Remove Duplicate Letters ✅The goal is to remove duplicate letters so that every letter appears once, ensuring the result is the smallest in lexicographical order among all possible results. 🧠 My Approach & Implementation Steps: To solve this efficiently in O(n) time, I used a Greedy approach supported by a Monotonic Stack: 1️⃣Frequency Map: First, I built a frequency array freq[26] to keep track of the remaining count of each character in the string. This tells the algorithm if a character can be safely removed and re-added later. 2️⃣Visited Tracking: I used a boolean array visited[26] to ensure each character is added to our result only once, maintaining the "unique" constraint. 3️⃣Monotonic Stack Logic: As I iterated through the string: I decremented the character's frequency. If the character was already in the stack, I skipped it. 4️⃣The Crucial Part: While the current character was smaller than the top of the stack AND that top character appeared again later in the string (checked via the frequency map), I popped the stack and marked that character as "not visited." 💯Result Construction: Finally, I pushed the current character onto the stack and built the final string using a StringBuilder. 📊 Results: Runtime: 2 ms (Beats 89.98%) Memory: 43.64 MB (Beats 78.91%) ⚡This problem is a great reminder of how powerful stacks can be when you need to maintain a specific order while processing linear data. Onward to the next challenge! 💻🔥 #LeetCode #Java #DataStructures #Algorithms #CodingLife #ProblemSolving #SoftwareEngineering Anchal Sharma Ikshit ..

  • graphical user interface

To view or add a comment, sign in

Explore content categories