[Python Code] First Repeated Character in String and Count

[Python Code] First Repeated Character in String and Count

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.

Python program

Prerequisites:

Code:

Python

Output:

The first repeated character is 's' and it occurred 3 times.

The first repeated character here is ‘s’ which occurred three times.

Explanation

  • We are initializing the designed character desired_ch as empty.
  • As soon as we find the first occurrence of a repeated character, assign that character to the designed character desired_ch.
  • dictionary char_count saves the number of occurrences for each character.
  • As soon as we find the desired character, we just count the occurrence of the desired character and update it in the chart_count dictionary. And ignoring all other characters.

Complexity:

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!

Leave a Reply

Your email address will not be published. Required fields are marked *

StatCounter - Free Web Tracker and Counter