Optimized DSA Practice: Finding First Non-Repeating Character with ASCII Array

🚀 DSA Practice – find the first non -repeating character. While solving a string problem related to character frequency, I first thought of using a HashMap. But then I optimized it further by using an array based on ASCII values — which is faster and more memory-efficient. 💡 Optimized Approach (Using ASCII Array) 🔹 Step 1: Use an integer array of size 256 Since characters are stored internally using ASCII values, we can directly use an array where the index represents the character. ```java int[] freq = new int[256]; ``` 🔹 Step 2: Store frequency using ASCII index Traverse the string once and increment the count using the character’s ASCII value. ```java for (char ch : str.toCharArray()) { freq[ch]++; } ``` Here, `ch` automatically converts to its ASCII integer value, making access O(1) without hashing overhead. 🔹 Step 3: Find the required character while preserving order Traverse the string again and check which character has frequency = 1. ```java for (char ch : str.toCharArray()) { if (freq[ch] == 1) { System.out.println("Answer: " + ch); break; } } `` 🧠 Why This is More Optimized Than HashMap ✅ No hashing overhead ✅ Faster lookups (direct index access) ✅ Lower memory usage compared to HashMap objects ✅ Time Complexity: O(n) ✅ Space Complexity: O(1) (fixed array size – 256) This approach shows how understanding how characters are stored internally (ASCII/Unicode) can help write even more efficient code. Small optimizations like this can make a big difference in performance-critical applications. 💯 #DSA #Java #OptimizedCode #ProblemSolving #CodingPractice

To view or add a comment, sign in

Explore content categories