First Unique Character in a String – Leetcode Solution

In this post, we are going to solve the 387. First Unique Character in a String problem of Leetcode. This problem 387. First Unique Character in a String is a Leetcode easy level problem. Let’s see code, 387. First Unique Character in a String – Leetcode Solution.

We provide the solution to this problem in 3 programming languages i.e. Java, C++ & Python.

Problem

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

Example 1 :


Input: s = "leetcode"
Output: 0

Example 2 :


Input: s = "loveleetcode"
Output: 2

Example 3 :


Input: s = "aabb"
Output: -1

Constraints

  • 1 <= s.length <= 105
  • s consists of only lowercase English letters.

Now, let’s see the code of 387. First Unique Character in a String – Leetcode Solution.

First Unique Character in a String – Leetcode Solution

387. First Unique Character in a String – Solution in Java

class Solution {
    public int firstUniqChar(String s) {
        int min = Integer.MAX_VALUE;
        for(char ch : s.toCharArray()){
            int index = s.indexOf(ch);
            
            if(index != -1 && index == s.lastIndexOf(ch)){
                min = Math.min(min,index);
            }
        }
        if(min == Integer.MAX_VALUE) return -1;
        return min;
    }
}

387. First Unique Character in a String – Solution in C++

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

387. First Unique Character in a String – Solution in Python

class Solution(object):
    def firstUniqChar(self, s):
        
        freq = Counter(s)
        
        for e in s :
            if freq[e] == 1 :
                return s.index(e)
            
        return -1

Note: This problem 387. First Unique Character in a String is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *