Find the first repeating character in a string.
ReportedSource: GeeksforGeeks interview experience: Deloitte Product Engineering Analyst 2024
Scan with a seen-set and return the first character already in the set (O(n)); if they mean the repeating character that appears earliest, count first and return the first char with count > 1. Clarify which.
Constraints
- Input: one line with the string s (may be empty). Characters are case sensitive; spaces count as characters.
- 0 <= len(s) <= 100000.
- Output: the first character whose second occurrence appears earliest, or the word none when all characters are different.
Sample I/O
in: abcbad
out: b
in: abcdef
out: none
in: hello
out: l
Sign up to run your code in the sandbox.
Sign up to run code and get an AI review
You can read and edit the challenge freely — running it in the sandbox and getting AI feedback need a free account.
Sign up freeHints
Reference solution
Definition to confirm. Usually: the first character (scanning left to right) that has already appeared earlier, i.e. whose second occurrence comes first. Some interviewers instead mean the character whose first occurrence is earliest among those that repeat; ask.
Second-occurrence version, O(n).
def first_repeating(s):
seen = set()
for ch in s:
if ch in seen:
return ch
seen.add(ch)
return None
"abcbad" returns 'b' (its second occurrence at index 3 comes before 'a''s at index 4).
Earliest-first-occurrence version. Count all characters first, then return the first character in the string whose count is > 1. For "abcbad" this returns 'a'.
Complexity. O(n) time, O(k) space for the alphabet.
Edge cases. No repeats (return None or -1), case sensitivity, spaces and punctuation.