Find the Difference in C++


Suppose we have two strings s and t which consist of only lowercase letters. Now, string t is generated by random shuffling string s and then add one more letter at a random index. We have to find the letter that was added in t.

So, if the input is like "mnopq","pqmnot", then the output will be "t", this is the extra letter.

To solve this, we will follow these steps −

  • sSum := 0, tSum := 0

  • for initialize i := 0, when i < call length() of s, update (increase i by 1), do −

    • sSum := sSum + s[i]

  • for initialize j := 0, when j < call length() of t, update (increase j by 1), do −

    • tSum := tSum + t[j]

  • return (tSum - sSum) as character

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   char findTheDifference(string s, string t) {
      int sSum = 0;
      int tSum = 0;
      for (int i = 0; i < s.length(); i++) {
         sSum += s[i];
      }
      for (int j = 0; j < t.length(); j++) {
         tSum += t[j];
      }
      return char(tSum - sSum);
   }
};
main(){
   Solution ob;
   cout << (ob.findTheDifference("mnopq","pqmnot"));
}

Input

"mnopq","pqmnot"

Output

t

Updated on: 10-Jun-2020

215 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements