Skip to content

2351. First Letter to Appear Twice 👍

  • Time: $O(n)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  char repeatedCharacter(string s) {
    vector<bool> seen(26);

    for (const char c : s) {
      if (seen[c - 'a'])
        return c;
      seen[c - 'a'] = true;
    }

    throw;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public char repeatedCharacter(String s) {
    boolean[] seen = new boolean[26];

    for (final char c : s.toCharArray()) {
      if (seen[c - 'a'])
        return c;
      seen[c - 'a'] = true;
    }

    throw new IllegalArgumentException();
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def repeatedCharacter(self, s: str) -> str:
    seen = [False] * 26

    for c in s:
      if seen[string.ascii_lowercase.index(c)]:
        return c
      seen[string.ascii_lowercase.index(c)] = True