Find the index of the first unique character in a given string using C++


Given a string ‘s’, the task is to find the first unique character which is not repeating in the given string of characters and return its index as output. If there are no such characters present in the given string, we will return ‘-1’ as output. For example,

Input-1

s = “tutorialspoint”

Output

1

Explanation − In the given string “tutorialspoint”, the first unique character which is not repeating is ‘u’ which is having the index ‘1’. Thus we will return ‘1’ as output.

Input-2

s = “aaasttarrs”

Output

-1

Explanation − In the given string “aaasttarrs’, there are no unique characters. So, we will return the output as ‘-1’.

The approach used to solve this problem

To find the index of the first unique character present in the given string, we can use the hashmap. The idea is to go through all the characters of the string and create a hashmap with Key as the character and Value as its occurrences.

While traversing through each character of the string, we will store the occurrences of each character if it appears. It will take O(n) linear time to store the occurrences of each character. Then we will go through the hashmap and will check if there is any character whose frequency is less than 2 or equal to ‘1’. And we will return the index of that particular character.

  • Take a string ‘s’ as an Input.

  • An Integer function uniqueChar(string str) takes a string as an input and returns the index of the first appearing unique character.

  • Iterate over the string and create a hashmap of char and its occurrences while going through each of the characters of the string.

  • If there is a character whose frequency is less than 2 or equal to 1, then return the index of that particular character.

  • If there are no unique characters present in the string, return ‘-1’ as Output.

Example

#include<bits/stdc++.h>
using namespace std;
int uniqueChar(string str){
   int ans = -1;
   unordered_map<char,int>mp;
   for(int i=0;str[i]!='\0'){
      mp[str[i]]++;
   }
   for(int i=0;i<s.size();i++){
      for(auto it= mp.begin();it!=mp.end();it++){
         if(it->first==str[i] && it->second==1){
            ans= i;
         }
      }
   }
   return ans;
}
int main(){
   string s= "tutorialspoint";
   cout<<uniqueChar(s)<<endl;
   return 0;
}

Output

Running the above code will print the output as,

1

Explanation − The input string ‘tutorialspoint’ contains the unique characters as ‘u’, ’r’, and ‘l’, and the first unique character ‘u’ has the index ‘1’. So, we get ‘1’ as the output.

Updated on: 05-Feb-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements