First Character Appearing Only Once

Implement a function to find the first character in a string which only appears once. For example: It returns ‘D’ when the input is “AamolDGoteAamolGote”. Typical solution for this problem may be scanning the input string from its beginning to end. We compare the current scanned character with every one behind it. If there is no duplication after it, it is a character appearing once. Since it compares each character with O(n) ones behind it, the overall time complexity is O(n2) if there are n characters in a string. Instead of doing this we can follow the approach using Hash tables, we can implement a hash table, in which keys are characters and values are their occurrence times in a string. It is necessary to scan strings twice: When a character is visited, we increase the corresponding occurrence time in the hash table during the first scanning. In second round of scanning, whenever a character is visited we also check its occurrence time in the hash table. The first character with occurrence time 1 is the required output.

        private static void FirstCharacterAppearingOnlyOnce(string input)
        {
            char[] inputCharacters = input.ToCharArray();
            IDictionary<char, int> characterCount = new Dictionary<char, int>();
            foreach (char c in inputCharacters)
            {
                if (characterCount.ContainsKey(c))
                {
                    characterCount[c] = ++characterCount[c];
                }
                else
                {
                    characterCount.Add(c, 1);
                }
            }

            foreach (char c in characterCount.Keys)
            {
                if (characterCount[c] == 1)
                {
                    Console.WriteLine("First Character Appearing Only Once is: " + c.ToString());
                    return;
                }
            }
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s