[Solved] Find First Duplicate Character in String in Python

[Solved] Find First Duplicate Character in String in Python

Problem Statement:

Write a program to find and print the first duplicate/repeated character in the given string.

Algorithm:

  1. Take a empty list (says ‘li_map’).
  2. Loop over all the character (ch) in the given string. (Using for-loop)
    1. if the ‘ch’ is present in ‘li_map’, return ‘ch’ (first duplicate character)
    2. Otherwise, add ‘ch’ in the ‘li_map’ list.

Program to Find First Duplicate Character in String in Python:

Prerequisite:

  • 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.

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

Complexity:

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:

Leave a Reply

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