Prepin
Log in

Identify the first character that repeats in the provided string.

Approach / Explanation

This task requires you to identify the first character that appears more than once in a specified string. It's important to note that the comparison is case-sensitive, meaning 'A' and 'a' are treated as distinct characters. Additionally, if there are no repeating characters, the function should return None or a specific message indicating this. To tackle this problem, you can follow these steps: Begin by defining a function that accepts the string as an input. Loop through the string from left to right, and for each character: Determine if this character has already been encountered (check if it exists in your storage structure, such as a set, list, or dictionary). If it has been seen before, return it as the first repeated character. If it has not been seen, add it to your structure to track that this character has now been observed. If no characters are repeated, return None or a message that conveys this information.

Suggested Answer

Below is an example of code you could utilize to address this question: def first_repeated_char ( s ) : char_set = set ( ) for char in s : if char in char_set : return char else : char_set . add ( char ) return None print ( first_repeated_char ( 'abca' ) ) # 'a' print ( first_repeated_char ( 'abcdef' ) ) # None In this approach, a set named 'char_set' is utilized to keep track of characters found in the string. If a character already exists in the set, that character is identified as the first repeated character and is returned by the function. If there are no repeated characters, the function will return None.

Alternative Answer

Here’s another illustration that utilizes a dictionary rather than a set: def first_repeated_char ( s ) : char_dict = { } for char in s : if char in char_dict : return char else : char_dict [ char ] = 1 return "No repeated character found." print ( first_repeated_char ( 'abca' ) ) # 'a' print ( first_repeated_char ( 'abcdef' ) ) # "No repeated character found." This solution is conceptually similar to the previous one. However, it employs a dictionary to keep track of the characters instead of a set, allowing for the possibility of more intricate conditions if necessary. Additionally, this example provides a specific message when no repeated character is identified.

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.