Consider the following C# code that counts the frequency of characters in a string. What will be printed?
using System; using System.Collections.Generic; class Program { static void Main() { string input = "banana"; Dictionary<char, int> freq = new Dictionary<char, int>(); foreach (char c in input) { if (freq.ContainsKey(c)) { freq[c]++; } else { freq[c] = 1; } } foreach (var pair in freq) { Console.WriteLine($"{pair.Key}: {pair.Value}"); } } }
Count how many times each letter appears in "banana".
The letter 'b' appears once, 'a' appears three times, and 'n' appears twice.
This code updates the frequency of numbers in an array. What is the final frequency dictionary?
using System; using System.Collections.Generic; class Program { static void Main() { int[] nums = {1, 2, 2, 3, 3, 3}; Dictionary<int, int> freq = new Dictionary<int, int>(); foreach (int num in nums) { if (freq.ContainsKey(num)) { freq[num] += 1; } else { freq[num] = 1; } } freq[2] += 2; foreach (var pair in freq) { Console.WriteLine($"{pair.Key}: {pair.Value}"); } } }
Remember to add 2 more to the count of number 2 after counting.
Initially, 2 appears twice, then 2 is added, making total 4.
Given two strings, which code snippet correctly uses frequency counters to check if they are anagrams?
Anagrams have the same character counts for each letter.
Using frequency dictionaries for both strings and comparing them ensures all characters and counts match.
Analyze the code below. What error will it raise when run?
using System; using System.Collections.Generic; class Program { static void Main() { string s = null; Dictionary<char, int> freq = new Dictionary<char, int>(); foreach (char c in s) { if (freq.ContainsKey(c)) { freq[c]++; } else { freq[c] = 1; } } } }
Consider what happens when you try to loop over a null string.
Trying to iterate over a null string causes a NullReferenceException.
After running the frequency counter on the string "abracadabra", how many unique characters does the frequency dictionary contain?
using System; using System.Collections.Generic; class Program { static void Main() { string input = "abracadabra"; Dictionary<char, int> freq = new Dictionary<char, int>(); foreach (char c in input) { if (freq.ContainsKey(c)) { freq[c]++; } else { freq[c] = 1; } } Console.WriteLine(freq.Count); } }
Count distinct letters in "abracadabra".
The unique letters are a, b, r, c, d. There are 5 unique characters.
