In C#... O(n) time complexity...
public char GetFirstRecuringChar(string text)
{
if (string.IsNullOrEmpty(text) || string.IsNullOrWhiteSpace(text))
{
throw new ArgumentNullException();
}
IDictionary<char, CharIndex> map = new Dictionary<char, CharIndex>();
for (int i = 0; i < text.Length; i++)
{
if (map.ContainsKey(text[i]))
{
map[text[i]].Count++;
}
else
{
CharIndex ci = new CharIndex { Index = i, Ch = text[i], Count = 1 };
map.Add(text[i], ci);
}
}
int lowestIndex = int.MaxValue;
foreach (CharIndex charIndex in map.Values)
{
if (charIndex.Count == 1)
{
if (lowestIndex > charIndex.Index)
{
lowestIndex = charIndex.Index;
}
}
}
char answer = '\n';
if (lowestIndex != int.MaxValue)
{
foreach (CharIndex charIndex in map.Values)
{
if (charIndex.Index == lowestIndex)
{
answer = charIndex.Ch;
break;
}
}
}
return answer;
}
private class CharIndex
{
public char Ch { get; set; }
public int Index { get; set; }
public int Count { get; set; }
}
Unit tests:
[TestCase("ississippitotalm", 'o')]
[TestCase("a", 'a')]
[TestCase("teeter", 'r')]
[TestCase("teeterxyz", 'r')]
[TestCase(".......................................x.................f.........y...xkiuytreeee", 'f')]
public void GetFirstRecuringCharTest(string text, char expectedAnswer)
{
char result = runner.GetFirstRecuringChar(text);
Assert.That(result, Is.EqualTo(expectedAnswer));
}