Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
first_unique('leetcode')  # 0
first_unique('loveleetcode')  # 2
I came up with the following solution. How can I make it more efficient for very long input strings?
def first_unique(self, s):
    if s == '':
        return -1
    for item in s:
        if s.count(item) == 1:
            return s.index(item)
            break
    return -1
My solution uses Counter form the collections module.
from collections import Counter
def first_unique(s):
    c = Counter(s)
    for i in range(len(s)):
        if c[s[i]] == 1:
            return i
    return -1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With