v9.1.1
Menu

First Unique Character in a String

easyPROStreaming & QueuesNetflix DSA

Given a string s, find the first non-repeating character and return its index. Return -1 if no such character exists.

Example

Input
leetcode
Output
0
Reasoning
  • Input: s is the string leetcode, eight lowercase letters at positions 00 through 77: l, e, e, t, c, o, d, e.
  • Which letters repeat: "e" occurs 33 times (positions 11, 22 and 77). Every other letter, namely l, t, c, o and d, occurs exactly once.
  • Candidates: the non-repeating letters sit at positions {0,3,4,5,6}\{0, 3, 4, 5, 6\}. A letter qualifies only by its count across the whole string, so "e" at position 11 is ruled out even though its later copies come after it.
  • Output: the smallest candidate position is 00 (the letter "l"), so the answer is 0, an index, not the character itself.
  • Notice: "first" means earliest in the string, not alphabetically first ("c" would win alphabetically). If every letter repeats, as in "aabb", there is no candidate and the answer is −1-1.

Constraints

  • 1 <= len(s) <= 10^5
  • s consists of lowercase English letters

More from Netflix DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.