Problem statement:
Write a Python program to find the first repeated character in a given string and also print the number of times it has occurred.
This coding question was asked in the CGI interview for a Senior Backend developer.
Prerequisites:
Code:
def first_repeated_count(sample): desired_ch="" char_count={} for ch in sample: if not desired_ch: if ch not in char_count: char_count[ch] = 1 else: char_count[ch] += 1 desired_ch = ch else: if ch == desired_ch: char_count[ch] += 1 return (desired_ch, char_count[desired_ch]) if desired_ch else (None, 0) repeated_ch, count = first_repeated_count("designsystem") print(f"The first repeated character is '{repeated_ch}' and it occurred {count} times.")
Output:
The first repeated character is 's' and it occurred 3 times.
The first repeated character here is ‘s’ which occurred three times.
desired_ch
as empty.desired_ch
.char_count
saves the number of occurrences for each character.chart_count
dictionary. And ignoring all other characters.We are using Python for-loop to traverse each character once, the complexity of this algorithm is O(n)
.
Regarding the Python program to find the first repeated character, if you have any doubts or have a question, please write me in the comment. Good luck and happy coding!