Skip to content

387. First Unique Character in a String 👍

  • Time: $O(n)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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;
  }
}
1
2
3
4
5
6
7
8
9
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