Print characters having odd frequencies in order of occurrence in C++


In this problem, we are given string str by the user. And we have to print only those characters whose frequencies of occurrence in an odd number.

To solve this problem, we have to find the total frequency of occurrence of a character in a string. And print only those characters of the string that have odd frequencies of occurrence.

Let’s take an example to understand the topic better −

Input : adatesaas.
Output : dte

Explanation −The characters with their frequency of occurrence are −

a4
d1
t1
e1
s2

Characters with odd frequency are d, t, e.

Algorithm

Now let's try to create an algorithm to solve this problem −

Step 1 : Traverse the string and count the number of occurrences on characters of the string in an array.
Step 2 : Traverse the frequency array and print only those characters whose frequency of occurrence is odd.

Example

Let's create a program based on this algorithm −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   string str = "asdhfjdedsa";
   int n = str.length();
   int frequency[26];
   memset(frequency, 0, sizeof(frequency));
   for (int i = 0; i < n; i++)
      frequency[str[i] - 'a']++;
   for (int i = 0; i < n; i++) {
      if (frequency[str[i] - 'a'] % 2 == 1) {
         cout << str[i]<<" , ";
      }
   }
   return 0;
}

Output

d , h , f , j , d , e , d

Updated on: 03-Jan-2020

331 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements