First Unique Character in a String

 https://leetcode.com/problems/first-unique-character-in-a-string/

class Solution {
public:
    int firstUniqChar(string s) {
       unordered_map<char,int>m;
        for(int i=0;i<s.length();i++){  //traversed and stored in map the char and its count
            m[s[i]]++;
        }
        for(int j=0;j<s.length();j++){ //traversed again and find the first index where the the m[s[i]]==1
            if(m[s[j]]==1){
                return j;
            }
        }
        return -1;
    }
}; 


class Solution {
public:
    int firstUniqChar(string s) {
       unordered_map<char,pair<int,int>>m;
        int n=s.size();
        for(int i=0;i<n;i++){
            m[s[i]].first++; //store the count
            m[s[i]].second=i;//store the index
        }
        for(auto &i:m){
            if(i.second.first==1) n=min(n,i.second.second); //in map if the count of any char is one find min index
        }
        return n==s.size()?-1:n; // return -1 if last loop is not executed
    }
};

Comments

Popular posts from this blog

Perfect Peak of Array

Is Rectangle?

Sort array with squares!