Problem
Given a strings, find the first non-repeating character in it and return its index. If it does not exist, return -1.
Examples
Constraints
1 <= s.length <= 10^5sconsists of only lowercase English letters.
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 387 with 20 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 387 # by problem number
lcpy gen -s first_unique_character_in_a_string # by problem name
s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
Input: s = "leetcode"
Output: 0
Explanation: The character 'l' at index 0 is the first character that does not occur at any other index.
Input: s = "loveleetcode"
Output: 2
Input: s = "aabb"
Output: -1
1 <= s.length <= 10^5s consists of only lowercase English letters.from collections import Counter
class Solution:
# Time: O(n)
# Space: O(1)
def first_uniq_char(self, s: str) -> int:
counts = Counter(s)
for i, ch in enumerate(s):
if counts[ch] == 1:
return i
return -1
| Time | Space |
|---|---|
| O(n) | O(1) |