➜ ~

Playing Hacks and Stuffs!


Project maintained by h4ckyou Hosted on GitHub Pages — Theme by mattgraham

First Unique Character in a String

image

To solve this I implemented Hashtable Data Structure and here’s the solve script link image

Another way to go about this is via Queue Data Structure

And here’s the implementation

from collections import Counter, deque

def firstUniqChar(s):
    c = Counter(s)
    q = deque()
    r = 0

    for char in s:
        q.append(char)
        if c[q[0]] > 1:
            while q and c[q[0]] > 1:
                q.popleft()
                r += 1
        else:
            return r
        
    return -1

s = "loveleetcode"
r = firstUniqChar(s)
print(r)