wasAsked.

Write code to find duplicates of each character and it's count in the word "findtheduplicatesinword"

HCA Healthcare · Role not specified · technical

Published

Year not specified · Software Engineering

Community answers

Posted by wasAsked editorial collection

The word "findtheduplicatesinword" contains repeated letters. Counting each character and showing those that appear more than once: Using a Dictionary (clear and efficient, O(n)) string word = "findtheduplicatesinword"; var counts = new Dictionary<char, int>(); foreach (char ch in word) counts[ch] = counts.TryGetValue(ch, out var c) ? c + 1 : 1; foreach (var (ch, count) in counts) if (count > 1) Console.WriteLine($"{ch}: {count}"); Output (in order of first appearance): i: 3 n: 2 d: 3 t: 2 e: 2 Using LINQ (concise) var duplicates = word.GroupBy(ch => ch) .Where(g => g.Count() > 1) .Select(g => new { Char = g.Key, Count = g.Count() }); foreach (var d in duplicates) Console.WriteLine($"{d.Char}: {d.Count}"); .NET 9+ offers CountBy: foreach (var (ch, count) in word.CountBy(c => c).Where(kv => kv.Value > 1)) Console.WriteLine($"{ch}: {count}"); Using an array for lowercase letters only (fastest, no allocations per character) int[] freq = new int[26]; foreach (char ch in word) freq[ch - 'a']++; for (int i = 0; i < 26; i++) if (freq[i] > 1) Console.WriteLine($"{(char)('a' + i)}: {freq[i]}"); This prints in alphabetical order: d: 3, e: 2, i: 3, n: 2, t: 2. Discussion points - Time complexity O(n) for the dictionary and array approaches; the LINQ GroupBy is also O(n) but allocates more. - Case sensitivity: normalise with char.ToLowerInvariant if "A" and "a" should count together. - Ignore spaces or punctuation when processing sentences (char.IsLetter). - If you also need all character counts (not only duplicates), drop the count > 1 filter. - Order of output: Dictionary preserves insertion order in practice for this scenario but does not guarantee it by contract; use the array approach or OrderBy if a specific order is required.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics