Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.
You may return the answer in any order.
Example 1:
Input: ["bella","label","roller"]
Output: ["e","l","l"]
Example 2:
Input: ["cool","lock","cook"]
Output: ["c","o"]
Note:
1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j] is a lowercase letter
Solution:
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode.AskGif.Easy.Array
{
public class CommonCharsSoln
{
public IList<string> CommonChars(string[] A)
{
var mapList = new List<Dictionary<char, int>>();
for (int i = 0; i < A.Length; i++)
{
var map = new Dictionary<char, int>();
for (int j = 0; j < A[i].Length; j++)
{
if (map.ContainsKey(A[i][j]))
{
map[A[i][j]]++;
}
else
{
map.Add(A[i][j], 1);
}
}
mapList.Add(map);
}
var res = new List<string>();
for (char i = 'a'; i <= 'z'; i++)
{
int min = int.MaxValue;
for (int j = 0; j < mapList.Count; j++)
{
if (mapList[j].ContainsKey(i))
{
if (mapList[j][i] < min)
{
min = mapList[j][i];
}
}
else
{
min = 0;
}
}
if(min == int.MaxValue)
{
min = 0;
}
for (int x = 0; x < min; x++)
{
res.Add(i.ToString());
}
}
return res;
}
}
}
Time Complexity: O(m*n) Where m is the number of string and n is the size of the string.
Space Complexity: O(m*n)
Unit Tests:
using LeetCode.AskGif.Easy.Array;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
namespace CodingUnitTest.Easy.Array
{
[TestClass]
public class CommonCharsSolnTests
{
[TestMethod]
public void CommonCharsSoln_First()
{
var arr = new string[] { "bella", "label", "roller" };
var expected = new Dictionary<string, int>();
expected.Add("e",1);
expected.Add("l", 2);
var res = new CommonCharsSoln().CommonChars(arr);
AreEqual(expected, res);
}
[TestMethod]
public void CommonCharsSoln_Second()
{
var arr = new string[] { "cool", "lock", "cook" };
var expected = new Dictionary<string, int>();
expected.Add("c", 1);
expected.Add("o", 1);
var res = new CommonCharsSoln().CommonChars(arr);
AreEqual(expected, res);
}
private void AreEqual(Dictionary<string, int> expected, IList<string> res)
{
var map = new Dictionary<string, int>();
for (int i = 0; i < res.Count; i++)
{
if (map.ContainsKey(res[i]))
{
map[res[i]]++;
}
else
{
map.Add(res[i], 1);
}
}
foreach (var item in map)
{
Assert.IsTrue(expected.ContainsKey(item.Key));
Assert.AreEqual(expected[item.Key], item.Value);
}
foreach (var item in expected)
{
Assert.IsTrue(map.ContainsKey(item.Key));
Assert.AreEqual(map[item.Key], item.Value);
}
}
}
}



