First non-repeating character using one traversal of string in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to learn how to find the first non-repeating character in the given string. Let's see an example.

Input −tutorialspoint

Output −u

Let's see the steps to solve the problem.

  • Initialize the string.

  • Initialize a map char and array to store the frequency of the characters in the string.

  • Iterate over the string.

  • Find the frequency of each character and store them in the map.

  • Store the index of the character as well.

  • Iterate over the character frequencies in the map.

  • Print the first character with the frequency 1.

Example

Let's see the code.

#include <bits/stdc++.h>
#include <map>
using namespace std;
void findDistinctCharacters(string random_string) {
   // initializing char count
   map<char, int[2]> chars;
   // iterating over the string
   for (int i = 0; i < random_string.size(); ++i){
      chars[random_string[i]][0]++;
      chars[random_string[i]][1] = i;
   }
   int char_index = INT_MAX;
   // printing the first char with frequency 1
   for (auto item: chars) {
      // checking the frequency
      if (item.second[0] == 1) {
         char_index = min(char_index, item.second[1]);
      }
   }
   // printing the first char with frequency 1
   cout << random_string[char_index] << u;
}
int main() {
   findDistinctCharacters("tutorialspoint");
   return 0;
}

Output

If you run the above code, then you will get the following result.

u

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 29-Dec-2020 15:39:29
Advertisements