Removing Duplicate Characters in Strings with Boolean Array

🚀 DSA Series – Problem Solving Today I solved a classic String problem: Removing Duplicate Characters. 🧩 Problem Statement Given a string, remove duplicate characters while maintaining the order of first occurrence. Example: Input: `"programming"` Output: `"progamin"` 🧠 Optimized Approach (Using Boolean Array) Instead of using a HashSet, I used a boolean array to track characters. This works great when the character set is limited (like ASCII). 🔹 Step-by-step Logic 1️⃣ Create a boolean array of size 256 (for all ASCII characters). * Each index represents a character. * Default value is `false` → means character not seen yet. 2️⃣ Create a StringBuilder to store the result. 3️⃣ Traverse the string character by character: * For each character `ch`, check `if (seen[ch] == false)` → Mark it as seen: `seen[ch] = true` → Append it to StringBuilder * If already `true`, skip it (duplicate). 4️⃣ Convert StringBuilder to string — final answer ready ✅ ⏱ Time & Space Complexity Time Complexity: O(n) We traverse the string only once. Space Complexity:O(1) Because the boolean array size is fixed (256), not dependent on input size. 💡 Key Learning Choosing the right data structure matters a lot. Boolean arrays can be faster and more memory-efficient than HashSet when the character range is small. Small optimizations = Big performance impact 🚀 #DSA #Java #ProblemSolving #CodingJourney #Placements #LearningInPublic

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories