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

  1. Problem Statement
  2. Complexity Analysis
  3. First Unique Character in a String solution in C++
  4. First Unique Character in a String solution in Java
  5. First Unique Character in a String solution in Python
  6. Additional Resources
387. First Unique Character in a String LeetCode Solution image

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

See also  745. Prefix and Suffix Search LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.