Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

387. First Unique Character in a String 🌟

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

O(N^2) Time and O(1) space

O(N) Time and O(N)=O(26) constant space

Code

class Solution{
public:
    int firstUniqChar(string s){
        unordered_map<char, int> mp;
        int n = s.size();
        for (auto &x : s) mp[x]++;
        for (int i = 0; i < n; i++){
            if (mp[s[i]] == 1) return i;
        }
        return -1;
    }
};