## Description

https://leetcode.com/problems/first-unique-character-in-a-string/description/

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

**Examples:**

1 2 3 4 5 |
s = "leetcode" return 0. s = "loveleetcode", return 2. |

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

## Explanation

We introduce an array with a length of 26 to save the number of times each character appears in the string.

The idea is to go through the string and save the number of times each character appears in the string. That would take $O(N)$ time, where `N`

is a number of characters in the string.

And then we go through the string the second time, this time we use the array as a reference to check if a character is unique or not. If the character is unique, one could just return its index. The complexity of the second iteration is $O(N)$ as well.

## Video Tutorial

## Java Solution

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class Solution { public int firstUniqChar(String s) { if (s == null || s.length() == 0) { return -1; } int[] charCounts = new int[26]; for (int i = 0; i < s.length(); i++) { charCounts[s.charAt(i) - 'a']++; } for (int i = 0; i < s.length(); i++) { if (charCounts[s.charAt(i) - 'a'] == 1) { return i; } } return -1; } } |

## Complexity Analysis

- Time complexity: $O(N)$ since we go through the string of length
`N`

two times. - Space complexity: $O(1$$)$ since we use an array with 26 elements.