Solved "Remove Duplicate Letters" with Stack and Greedy Algorithm

🌟 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

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories