Problem Statement:
Write a program to find and print the first duplicate/repeated character in the given string.
Prerequisite:
Other part of the code in this coding example is self explanatory.
Python Program:
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)
Output:
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: