Back to photostream

Find the Difference Leetcode Solution

Problem statement

In the problem "Find the Difference" we are given two strings s and t. String t is produced by randomly stuffing the characters of string s and adding one character at a random position.

 

our task is to find out the character which was added in string t.

Example

s = "abcd", t = "abcde"

e

Explanation:

 

After rearranging the characters of string t it becomes "abcde". As "abcd" is already present in string s, so the character that was added to t is "e".

Sorting Approach for Find the Difference Leetcode Solution

If we change our perspective to see the problem then sometimes it becomes easy to solve it. like here the problem says string t is generated by shuffling string s and adding one element at a random position. So, we can see this as string t is generated by adding a character at a random position in the string s. Now we only need to find out the position where the character of string s is not matching with the character of the string t and then we can return the character present at that position. So we will follow these steps:

 

- Sort both the string.

- Check character by character both the string and the point where they didn't match is the added character and that is the answer.

- If all characters matched then the character at the last position of string t is our answer.

 

Implementation

C++ code for Find the Difference

#include

using namespace std;

char findTheDifference(string s, string t) {

sort(s.begin(),s.

 

www.tutorialcup.com/leetcode-solutions/find-the-differenc...

60 views
0 faves
0 comments
Uploaded on October 14, 2021