DEV Community

Aroup Goldar Dhruba
Aroup Goldar Dhruba

Posted on • Edited on

1

LeetCode: First Unique Character in a String

Problem Statement

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Example

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.
Enter fullscreen mode Exit fullscreen mode

Note: You may assume the string contains only lowercase letters.

Solution Thought Process

This is a hash map problem. First, we count the frequency of the characters in the string by iterating over the string once. Then we iterate through the string again, this time if we find the frequency 1 of a character, we will set this as the answer and we break the loop. If no element's frequency which equals 1, we return -1 as the answer.

Solution

class Solution {
public:
    int firstUniqChar(string s) {
        unordered_map<char,int> M;
        for(int i=0;i<s.size();i++)
        {
            if(M.count(s[i]))
            {
                M[s[i]]++;
            }
            else {
                M[s[i]] = 1;
            }
        }
        int answer_index = -1;
        for(int i=0;i<s.size();i++)
        {
            if(M[s[i]]==1)
            {
                answer_index = i;
                break;
            }
        }
        return answer_index;
    }
};
Enter fullscreen mode Exit fullscreen mode

Complexity

Time Complexity: O(n), where n = length of s.

Space Complexity: O(n), where n = length of s.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay