Home » Interview Questions » String Interview Questions » Print all duplicates in the input string

Print all duplicates in the input string


()

Given an input string, write a function that will print all the duplicates in that string

Example

INPUT : “Tutorial cup”

OUTPUT :
t   count = 2
u count = 2

Here, t, u are th duplicate and they ocuured 2 times in the string

Time Complexity : O(n)

Algorithm

1. Scan the input string and construct a character count array from input string
ie, In the above example,
count of t is 2, so count[‘t’] = 2
count of u is 2, so count[‘u’] = 2
count of o is 1, so count[‘o’] = 1

2. Scan the input string and print all the indexes from the count array which have value greater than 1
ie, In above example,
indexes t, u have value greater than 1

C++ Program

#include <bits/stdc++.h>
#define NO_OF_CHARS 256
using namespace std;

void printDuplicates(string s)
{
	int count[NO_OF_CHARS] = {}; 
	for(int i=0; i<s.size(); i++)
		count[s[i]]++; //increment the count of each character by using ASCII of character as key	
	for(int i=0; i<s.size(); i++)
		if(count[s[i]] > 1) //
			{
			cout<<s[i]<<"   count = "<<count[s[i]]<<endl;
			count[s[i]] = 0;
			}
}
int main()
{
	string s  = "tutorial cup";
	cout<<"Input string is "<<s<<endl;
	printDuplicates(s);
}

Try It

 

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote Count

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

READ  Valid Number
Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions