Finding Duplicate Characters in a String

Finding duplicate characters in a string

The Task is to find all the duplicate characters in the string and return the characters whose occurrence is more than 1.

We have to write a python code to traverse through the string input and check for reoccurrence of any character in the given input string. If a character is repeated or is present more than once, we append the character to the output list and print the output list. For instance,

  • Input:
    Namaste
  • Output:
    The duplicate characters are [‘a’]
Repeating Characters in a String

Finding duplicate Characters in a string

There are two approaches to finding duplicate characters in a string. One uses Dictionary and the other uses Lists. the two approaches are as follows:

  1. Using Dictionary 
  2. Using List
Program to find the Duplicate Characters in a String in Python

Method 1: Using Dictionary

Python code
#using dictionary
string = input()
dups={}
for x in string:
  if x not in dups:
    dups[x]=0
  else:
    dups[x]+=1
output=[]
for keys,vals in dups.items():
  if vals>0:
    output.append(keys)
print('The duplicate characters are {}'.format(output))
Output
shalalala
The duplicate characters are ['a', 'l']

Explanation

In the above code, we use dictionary containers and it’s properties to traverse through the string and point out the characters with more than one occurrence. 

The algorithm is as follows:

  1. Take string input using the input() function.
  2. Initialise an empty dictionary.
  3.  Iterate a for loop for string traversal.
  4. Check if the element is in the dictionary has the elements or not, if yes increment its count by 1. else add the character to the dictionary with count as 0.
  5. Iterate through the dictionary values using a for loop. if the element has counted more than 1, append it to the output list using the append() function.
  6. Print the output list.

The output is a list containing all the elements in the input string with more than one occurrence. 

Method 2: Using List

Python code
#using list
string = input()
dups=[]
for ch in string:
  if string.count(ch)>1 and ch not in dups:
    dups.append(ch)
print('The duplicate characters are {}'.format(dups))
Output
shalalala
The duplicate characters are ['a', 'l']

Explanation

The above code uses Lists and their properties to traverse and point out the characters that occur more than once in the given string. 

The algorithm for the above code is as follows:

  1. Take a string input using the input() function.
  2. Declare an empty list called dups.
  3. Iterate through the string using a for loop, using the .count() function check if the occurrence of a character is more than one in the giver string, if true, append it to the dups list. 
  4. Print the dups list.

The output is a list containing all the elements in the input string with more than one occurrence.