Print all duplicates in the input string

StringViews 2814

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)


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


Translate »