Skip to content
DeepForgeby svx
All problems
EasyData Structuresds-017

First Non-Repeating Character

Problem

Return the index of the first character in a string that does not repeat anywhere else.

Count how often each character occurs, then scan left to right for the first character whose count is one. Return -1 if no such character exists, including for the empty string.

Hint

Build a frequency map first, then scan the string again.

Test cases

case 1
in: ["leetcode"]
expected: 0
case 2
in: ["loveleetcode"]
expected: 2
case 3
in: ["aabb"]
expected: -1
case 4
in: [""]
expected: -1
case 5
in: ["z"]
expected: 0
Starter codePython
def first_unique_char(s):
    # Your code here
    pass

5 test cases · run your code against them in the editor