I wrote a solution to first-unique-character-in-a-string:

Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.

If there is better way for me to build the dictionary seems? and find the first key when value is 1 and index is lowest?

def firstUniqChar(string) -> int:
    seems = dict()
    index = len(string)
    c = ''
    for i, char in string:
        if char not in seems:
            seems.setdefault(char, (i,1))
            seems[char] = (seems[char][0], seems[char][1] + 1)

    for k, value in seems.items():
        if value[1] == 1 and value[0] < index:
            index = value[0]
            c = k
    return  index if c else -1

1 Answer 1


The code is too convoluted and unreadable for such a simple task

  • seems is a dictionary where the values are (first index, occurrences) pairs. That's an unconventional data structure. You'd be better off with two separate dictionaries.
  • seems is a weird variable name. What does it mean, anyway?
  • Why is the index = len(string) statement necessary?

This solution is less cluttered, and more clearly expresses the idea that you are counting the characters, then finding the first unique one.

from collections import Counter

def first_uniq_char(s):
    counts = Counter(s)
    return next((i for i, c in enumerate(s) if counts[c] == 1), -1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.