Kth Distinct String in Array with HashMap and Order Preservation

🚀 #100DaysOfCode – Day 19 Today’s challenge: Kth Distinct String in an Array 🔤 You’re given an array of strings and an integer k. Your task is to return the kth distinct string — a string that appears exactly once, while also respecting the original order. 🔴 Brute Force Approach For every string, count its occurrences by scanning the entire array Track distinct elements in order ⛔ Time Complexity: O(n²) 👉 Repeated counting makes it inefficient 🟢 Optimized Approach (HashMap + Order Preservation) 💡 Idea: First, count frequency of each string using a HashMap Then, iterate again to maintain original order Decrease k when a distinct string is found ✅ Code: class Solution { public String kthDistinct(String[] arr, int k) { Map<String, Integer> mp = new HashMap<>(); // Count frequency for (var s : arr) { mp.put(s, mp.getOrDefault(s, 0) + 1); } // Find kth distinct for (var s : arr) { if (mp.get(s) == 1) { k--; } if (k == 0) { return s; } } return ""; } } 🧠 Key Insight 👉 Use HashMap for frequency counting 👉 Use array traversal to preserve order This combination ensures: Efficient lookup Correct ordering ⚡ Complexity Time: O(n) Space: O(n) 🔍 Example arr = ["a","b","a","c","d","c"], k = 2 Distinct elements → ["b", "d"] 👉 Output = "d" 💡 Learning of the Day Efficiency is not just about speed — it’s about combining the right data structures with the right traversal strategy. #Day19 #100DaysOfCode #DSA #Java #HashMap #CodingJourney #LeetCode #ProblemSolving

To view or add a comment, sign in

Explore content categories