> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# First Unique Character in a String

> Tested Python solution for LeetCode 387 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 387, [Easy](/catalog/easy). Topics: [Hash Table](/catalog/topics/hash-table), [String](/catalog/topics/string), [Queue](/catalog/topics/queue), [Counting](/catalog/topics/counting). [View on LeetCode](https://leetcode.com/problems/first-unique-character-in-a-string/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 387   # by problem number
lcpy gen -s first_unique_character_in_a_string   # by problem name
```

## Problem

Given a string `s`, find the **first** non-repeating character in it and return its index. If it **does not** exist, return `-1`.

### Examples

```
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
```

### Constraints

* `1 <= s.length <= 10^5`
* `s` consists of only lowercase English letters.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/first_unique_character_in_a_string/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/first_unique_character_in_a_string/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
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
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(1) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.