Saturday, January 2, 2021

First Unique Character in a String

Problem: Given a string containing only lowercase English letters., find the first non-repeating character in it and return its index. If it doesn't exist, return -1.

Example:

s = "aabbcdd"
return 4.

s = "aabb"
return -1.


Approach: It's a straight forward problem to solve using hashing. Approach can be easily understood by just looking at the code.


Implementation in C#:

        public int FirstUniqChar(string s)

        {

            if (string.IsNullOrWhiteSpace(s))

            {

                return -1;

            }

            int[] hash = new int[26];

            for(int i = 0; i < s.Length; ++i)

            {

                if (hash[s[i] - 'a'] == 0)

                {

                    hash[s[i] - 'a'] = i + 1;

                }

                else if (hash[s[i] - 'a'] > 0)

                {

                    hash[s[i] - 'a'] = -1;

                }

            }

            int min = int.MaxValue;

            foreach(int num in hash)

            {

                if (num > 0 && num < min)

                {

                    min = num;

                }

            }

            return min == int.MaxValue ? - 1 : min - 1;

        }


Complexity: O(n)

No comments:

Post a Comment