[Solved] Find First Duplicate Character in String in Python
Write a program to find and print the first duplicate/repeated character in the given string.
- Take a empty list (says ‘li_map’).
- Loop over all the character (ch) in the given string. (Using for-loop)
- if the ‘ch’ is present in ‘li_map’, return ‘ch’ (first duplicate character)
- Otherwise, add ‘ch’ in the ‘li_map’ list.
Program to Find First Duplicate Character in String in Python:
- The for-loop in Python to check each character in the given string message.
- Python list– we are maintaining a list for adding a new character using append() method.
Other part of the code in this coding example is self explanatory.
def duplicate_char(msg): li_map =  for ch in msg: if ch in li_map: return ch else: li_map.append(ch) if __name__ == "__main__": ch = duplicate_char("Hello World!") print("First duplicate char is", ch)
First duplicate char is l
As we are checking each character in the string only once, the time complexity is O(n). Here ‘n’ is the number of characters in the string (length of the string).
We are maintaining separate list for adding characters. In worst case (if there is no duplicate or repeated character in the string), all the characters will be added in the list. So the space complexity is O(n), where n is the length of the string.
This is a simple program and best way to find first duplicate character in string in Python.
This question was asked in the Juniper interview.
Other Related Programming Questions: