First Letter to Appear Twice

easy bit manipulation bitmask string

Problem

Given a string s of lowercase English letters, return the first letter to appear twice. Letter a counts as appearing twice before letter b if the second occurrence of a comes before the second occurrence of b. Scanning left to right, the answer is simply the first character we land on that we have already seen.

Inputs = "abccbaacz"
Output"c"
At index 3 we read 'c', which already appeared at index 2. Its second occurrence is earlier than any other letter's, so 'c' is returned.

def repeatedCharacter(s):
    seen = 0                       # 26-bit mask of letters seen
    for ch in s:
        bit = 1 << (ord(ch) - ord('a'))
        if seen & bit:             # bit already set -> repeat
            return ch
        seen |= bit                # mark this letter as seen
    return ''                      # unreachable by constraints
function repeatedCharacter(s) {
  let seen = 0;                       // 26-bit mask of letters seen
  for (const ch of s) {
    const bit = 1 << (ch.charCodeAt(0) - 97);
    if (seen & bit) {                 // bit already set -> repeat
      return ch;
    }
    seen |= bit;                      // mark this letter as seen
  }
  return '';                          // unreachable by constraints
}
char repeatedCharacter(String s) {
    int seen = 0;                       // 26-bit mask of letters seen
    for (int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);
        int bit = 1 << (ch - 'a');
        if ((seen & bit) != 0) {        // bit already set -> repeat
            return ch;
        }
        seen |= bit;                    // mark this letter as seen
    }
    return ' ';                         // unreachable by constraints
}
char repeatedCharacter(string s) {
    int seen = 0;                       // 26-bit mask of letters seen
    for (char ch : s) {
        int bit = 1 << (ch - 'a');
        if (seen & bit) {              // bit already set -> repeat
            return ch;
        }
        seen |= bit;                    // mark this letter as seen
    }
    return ' ';                         // unreachable by constraints
}
Time: O(n) Space: O(1)