Medium csharp

Collections — Dictionary frequency map

Problem

Count word frequency with Dictionary<string,int>.

Hints
  • TryGetValue or ContainsKey

Your practice code

Ready — edit the code above and click Run.

Solution

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        string[] words = { "a", "b", "a", "c", "b", "a" };
        var freq = new Dictionary<string, int>();
        foreach (var w in words)
            freq[w] = freq.TryGetValue(w, out var c) ? c + 1 : 1;
        Console.WriteLine(freq["a"]);
    }
}

Try solving on your own first, then reveal the official answer.

Explanation

TryGetValue avoids double lookup—Dictionary interview best practice.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details