Print all duplicates in the input string  


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


INPUT : “Tutorial cup”

t   count = 2
u count = 2

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

Time Complexity : O(n)

Please click Like if you loved this article?


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;

Try It


See also
Expression Contains Redundant Bracket or Not
Please click Like if you loved this article?

Ads Blocker Image Powered by Code Help Pro
Ads Blocker Detected!!!

This website does not work properly with AdBlock. We have detected that you are using extensions to block ads. Please disable Adblocker to view the content.