[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:

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.

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 *