# 387\_First Unique Character in a String

\[easy] \[string, hash table]

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

**Note:**&#x59;ou may assume the string contain only lowercase letters.

**Examples:**

```
s = "leetcode"
return 0.

s = "loveleetcode",
return 2.
```

## Solution 1: brute force

**Idea**:

* Loop over each character from left to right, count the number of its occurrence. If it only occur once, return the index.&#x20;

**Time Complexity**: $$O(n^2)$$

**Space Complexity**: $$O(1)$$

```python
def firstUniqChar(s):
    """
    :type s: str
    :rtype: int
    """

    for i in range(len(s)):
        c = s[i]
        if s.count(c) == 1: # can write count as a helper function if needed
            return i
    return -1
```

## Solution 2: Use dictionary

**Idea**:

* Loop over each character from left to right.
* Store the character and its index in a dictionary if it's the first time it occur.
* If it occur more than once, store the character in another set.
* return the minimum index in the dictionary if exists.

**Time Complexity**: $$O(n)$$

**Space Complexity**: $$O(n)$$

```python
def firstUniqChar(s):
    """
    :type s: str
    :rtype: int
    """

    dict1 = {} # for characters appear once
    dict2 = set() # for characters appear more than once
    for i in range(len(s)):
        c = s[i]
        if c not in dict1 and c not in dict2:
            dict1[c] = i
        elif c in dict1:
            del(dict1[c])
            dict2.add(c)
    return min(dict1.values()) if len(dict1) > 0 else -1
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lei-d.gitbook.io/leetcode/string/387first-unique-character-in-a-string.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
