> For the complete documentation index, see [llms.txt](https://anton-veselskyi.gitbook.io/codding-problems-solutions/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://anton-veselskyi.gitbook.io/codding-problems-solutions/leetcode/easy/first-unique-character-in-a-string.md).

# First Unique Character in a String

## [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string)

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

**Examples:**

```

s = "leetcode"
return 0.

s = "loveleetcode"
return 2.
```

**Note:** You may assume the string contains only lowercase English letters.

## Solutions

### 🧠 Cpp

```cpp
class Solution
{
public:
    int firstUniqChar(string s)
    {
//         map<char, int> counter;

//         for(char ch : s)
//             counter[ch]++;

//         for(size_t i = 0; i < s.size(); ++i)
//             if(counter[s[i]] == 1)
//                 return i;


        int first_bitmask = 0, second_bitmask = 0;
        for(char ch : s)
        {
            const uint8_t ch_pos = ch - 'a';
            if(! (first_bitmask & 1 << ch_pos) )
               first_bitmask |= 1 << ch_pos;
            else
               second_bitmask |= 1 << ch_pos;
        }

        for(int i = 0; i< s.size(); ++i)
            if(  
               !(second_bitmask & 1 << (s[i] - 'a')) 
               && first_bitmask & 1 << (s[i] - 'a')
              )
                    return i;

         return -1;        
    }
};
```
