Leetcode: First Unique Character in A String


This question, although relatively simple, is asked very commonly at Bloomberg and Goldman Sachs.

Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. We clearly use a Hashmap here. Here are the examples, and I may assume a string only contains lowercase English letters. 

Examples:

s = "leetcode"

return 0.

s = "loveleetcode"

return 2.

With the characters 'L' and 'V', respectively. Case being closed, We definitely need to use a HashMap to answer this question

It uses either a HashMap or dictionary and marks everything that occurs in the characters.

Here's the code: 

class Solution {

    public int firstUniqChar(String s) {

        //occurances of characters for the alphabet

        HashMap<Character, Integer> count = new HashMap<Character, Integer>();

        int n = s.length();

        //iterate through each character of string, and put occurance

        for(int i = 0; i < n; i++) {

            char c = s.charAt(i); 

            count.put(c, count.getOrDeafult(c,0) + 1);

        }

        //get the first occurance

        for(int i = 0; i < n; i++) {

            if(count.get(s.charAt(i)) == 1) return i;

        }

        //no occurences occur

        return -1;

    }

}

The time complexity for this code is O(N) and the space complexity is O(1) because the English Alphabet contains 26 letters. 

Here's the code in Python: 

class Solution: 
    def firstUniqChar(self, s: str) -> int:
        #create hash map of character and how often it appears
        count = collections.Counter(s)
        #find the needed index
        for idx, ch in enumerate(s):
            if count[ch] == 1:
                return idx
        return -1 

Counter is the hash map, and enumerates iterates through the hash map.

Comments

Popular Posts