Python: Find the first repeated character of a given string where the index of first occurrence is smallest
Find repeated character with smallest index.
Write a Python program to find the first repeated character in a given string where the index of the first occurrence is smallest.
Visual Presentation:
Sample Solution:
Python Code:
# Define a function that finds the first repeated character in a string with the smallest distance between the repetitions.
def first_repeated_char_smallest_distance(str1):
temp = {} # Create an empty dictionary to store characters and their indices.
for ch in str1: # Iterate through each character in the input string.
if ch in temp: # If the character is already in the dictionary (repeated),
return ch, str1.index(ch) # Return the character and its first occurrence index.
else:
temp[ch] = 0 # Add the character to the dictionary with a value of 0 to mark its presence.
return 'None' # If no repeated character is found, return 'None'.
# Test the function with different input strings.
print(first_repeated_char_smallest_distance("abcabc")) # Output: ('a', 0) - 'a' is the first repeated character at index 0.
print(first_repeated_char_smallest_distance("abcb")) # Output: ('b', 1) - 'b' is the first repeated character at index 1.
print(first_repeated_char_smallest_distance("abcc")) # Output: ('c', 1) - 'c' is the first repeated character at index 1.
print(first_repeated_char_smallest_distance("abcxxy")) # Output: ('x', 3) - 'x' is the first repeated character at index 3.
Sample Output:
('a', 0) ('b', 1) ('c', 2) ('x', 3)
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to find the first repeated character based on the smallest first occurrence index using a dictionary.
- Write a Python program to scan a string and return the repeated character whose first occurrence is minimal.
- Write a Python program to use list comprehension and index() to identify the repeated character with the smallest initial index.
- Write a Python program to implement a function that compares indices of first occurrences of repeated characters and returns the one with the lowest index.
Python Code Editor:
Previous: Write a Python program to find the first repeated character in a given string.
Next:Write a Python program to find the first repeated word in a given string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics