Sparse Arrays

  • + 0 comments

    C# Solution

    {
            // Dictionary to store frequency of each string in the input list
            Dictionary<string, int> stringFrequency = new Dictionary<string, int>();
    
            // Populate the dictionary with the count of each string in the input list
            foreach (var str in strings)
            {
                if (stringFrequency.ContainsKey(str))
                {
                    stringFrequency[str]++;
                }
                else
                {
                    stringFrequency[str] = 1;
                }
            }
    
            // List to store the result for each query
            List<int> results = new List<int>();
    
            // Check the frequency of each query in the dictionary and add to results
            foreach (var query in queries)
            {
                if (stringFrequency.ContainsKey(query))
                {
                    results.Add(stringFrequency[query]);
                }
                else
                {
                    results.Add(0); // If the query is not in the dictionary, add 0
                }
            }
    
            return results;
        }