Start learning free

LESSON 226 OF 289 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Letter Count in C#: Counting with a Dictionary

Practice Read the full explanation

Given a string word, return a Dictionary that maps each letter of word to the number of times it appears in word.

Every letter of word is a key, and its value is how many times that letter appears. The order of the entries doesn't matter.

 

Example 1:

Input: word = "banana"
Output: {"b": 1, "a": 3, "n": 2}
Explanation: "b" appears once, "a" three times and "n" twice.

Example 2:

Input: word = "hello"
Output: {"h": 1, "e": 1, "l": 2, "o": 1}
Explanation: "l" appears twice; every other letter appears once.

Example 3:

Input: word = "a"
Output: {"a": 1}
Explanation: A single letter appears once.

 

Constraints:

  • word has at least one letter.
  • word is made of lowercase English letters, a to z.
  • Only the letters of word are keys: a letter that doesn't appear has no entry.
STEP 1 OF 5
    Ctrl + Enter to check

    C# · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Letter Count in C#, explained

    Problem overview

    The method LetterCount receives a string word and returns a Dictionary<char, int>. Each letter of the word is a key, and its value is the number of times that letter appears. A letter that doesn't occur has no entry, and the order of the entries doesn't matter.

    For "banana" the result has three entries: b is 1, a is 3 and n is 2. For "hello" it is h 1, e 1, l 2, o 1, and for "a" it is just a 1.

    Approach: a counting dictionary

    A dictionary maps keys to values, and here the key is a letter and the value is a tally. Go through the letters once. For each letter, either it has been seen before, and its tally goes up by one, or it is new, and its tally starts at 1.

    The two cases are needed because of how a Dictionary behaves. Reading a key that isn't there, as in counts[letter] += 1 on a new letter, throws a KeyNotFoundException. Writing to a key that isn't there is fine: counts[letter] = 1 adds the entry. So the code checks first with ContainsKey.

    Step by step

    1. Create an empty Dictionary<char, int> named counts. The key type is char and the value type is int.
    2. Write a foreach loop with a char named letter over word. A foreach over a string visits its characters one by one, like the items of an array.
    3. If counts.ContainsKey(letter) is true, add 1 with counts[letter] += 1. The letter was seen before, so it already has a tally.
    4. Otherwise set counts[letter] to 1. This is the first time the letter shows up.
    5. Return counts after the loop.

    The solution in C#

    class Solution {
        public Dictionary<char, int> LetterCount(string word) {
            Dictionary<char, int> counts = new Dictionary<char, int>();
            foreach (char letter in word) {
                if (counts.ContainsKey(letter)) {
                    counts[letter] += 1;
                } else {
                    counts[letter] = 1;
                }
            }
            return counts;
        }
    }

    On "banana" the loop meets b (new, tally 1), a (new, 1), n (new, 1), then a again (2), n again (2) and a once more (3). The returned dictionary holds b: 1, a: 3, n: 2.

    Details worth knowing:

    • Characters are written with single quotes in C# ('a'), strings with double quotes ("a"). The keys here are char values, so a test for the letter a looks up 'a'.
    • counts[letter] += 1 reads the current value, adds 1 and stores it back, so it is only safe when the key exists.
    • When printing a dictionary, the entries typically come out in the order they were added, but the order isn't something to rely on, and the lesson's tests don't depend on it.

    Complexity

    The loop runs once per letter, and ContainsKey and the indexer take constant time on average, so the time is O(n) for a word of n letters. The dictionary holds at most one entry per distinct letter, so the space is O(k) for k distinct letters, at most 26 here.

    Edge cases and common mistakes

    • Skipping the check. Writing counts[letter] += 1 alone throws a KeyNotFoundException on the first letter.
    • Setting instead of adding. Writing counts[letter] = 1 in every case leaves every tally at 1.
    • Using the wrong key type. A Dictionary<string, int> would need letter.ToString(). The method promises Dictionary<char, int>.
    • One letter. "a" gives a single entry with the value 1.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free