C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: With this optimization, we can avoid handling duplicate letters by keeping track of ones already encountered.
OptimizationThen: As each letter is encountered, its bit is tested. If it was already encountered, its bit will be set to 1.
Otherwise: We record the letter in the mask. The next time it is encountered we will recognize it.
C# program that checks duplicate letters
using System;
class Program
{
static void Main()
{
Console.WriteLine("Codex");
ReportDuplicateCharacters("Codex");
Console.WriteLine("massive");
ReportDuplicateCharacters("massive");
Console.WriteLine("mississippi");
ReportDuplicateCharacters("mississippi");
}
static void ReportDuplicateCharacters(string value)
{
int mask = 0;
for (int i = 0; i < value.Length; i++)
{
int index = value[i] - 97;
if ((mask & (1 << index)) != 0)
{
Console.WriteLine("Duplicate: {0}", value[i]);
}
else
{
mask |= (1 << index);
}
}
// To zero a bit: mask &= ~(1 << index);
}
}
Output
Codex
massive
Duplicate: s
mississippi
Duplicate: s
Duplicate: i
Duplicate: s
Duplicate: s
Duplicate: i
Duplicate: p
Duplicate: i
But: The mask approach here is more memory-efficient should you need to store this data somehow.