Find one extra character in a string using C++.


Suppose we have two strings S and T, the length of S is n, and the length of T is n + 1. The T will hold all characters that are present in S, but it will hold one extra character. Our task is to find the extra character using some efficient approach.

To solve this problem, we will take one empty hash table, and insert all characters of the second string, then remove each character from the first string, the remaining character is an extra character.

Example

 Live Demo

#include<iostream>
#include<unordered_map>
using namespace std;
char getExtraCharacter(string S, string T) {
   unordered_map<char, int> char_map;
   for (int i = 0; i < T.length(); i++)
      char_map[T[i]]++;
   for (int i = 0; i < S.length(); i++)
      char_map[S[i]]--;
   for (auto item = char_map.begin(); item != char_map.end(); item++) {
      if (item->second == 1)
      return item->first;
   }
}
int main() {
   string S = "PQRST";
   string T = "TUQPRS";
   cout << "Extra character: " << getExtraCharacter(S, T);
}

Output

Extra character: U

Updated on: 30-Oct-2019

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements