387. First Unique Character in a String LeetCode Solution
In this guide, you will get 387. First Unique Character in a String LeetCode Solution with the best time and space complexity. The solution to First Unique Character in a String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- First Unique Character in a String solution in C++
- First Unique Character in a String solution in Java
- First Unique Character in a String solution in Python
- Additional Resources

Problem Statement of First Unique Character in a String
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
Example 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.
Example 2:
Input: s = “loveleetcode”
Output: 2
Example 3:
Input: s = “aabb”
Output: -1
Constraints:
1 <= s.length <= 105
s consists of only lowercase English letters.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(26) = O(1)
387. First Unique Character in a String LeetCode Solution in C++
class Solution {
public:
int firstUniqChar(string s) {
vector<int> count(26);
for (const char c : s)
++count[c - 'a'];
for (int i = 0; i < s.length(); ++i)
if (count[s[i] - 'a'] == 1)
return i;
return -1;
}
};
/* code provided by PROGIEZ */
387. First Unique Character in a String LeetCode Solution in Java
class Solution {
public int firstUniqChar(String s) {
int[] count = new int[26];
for (final char c : s.toCharArray())
++count[c - 'a'];
for (int i = 0; i < s.length(); ++i)
if (count[s.charAt(i) - 'a'] == 1)
return i;
return -1;
}
}
// code provided by PROGIEZ
387. First Unique Character in a String LeetCode Solution in Python
class Solution:
def firstUniqChar(self, s: str) -> int:
count = collections.Counter(s)
for i, c in enumerate(s):
if count[c] == 1:
return i
return -1
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.