in there are given two strings s and t. string t is generated by random shuffling by random shuffling string s and then add one more letter at random position we need to write the logic to find the letter that was added in t and we return it
in this problem there all are in string s and t are small alphabets there ascii values start from 97 to 122 like this a=97,b=98,c=99........z=122 so let us assume s is source/starting and t is target/end in my approuch is prity simple adding sum of the source/ strating string in sum (int variable) and sum of target/end of in sum1(int variable) lets exaplain with example
input: s="abcd" and t="abcde"
output:"e"
explination:
in sum= a(97)+b(98)+c(99)+d(100)
total sum of ascii values of char in string s is 394 that store in sum=394
in sum1=a(97)+b(98)+c(99)+d(100)+e(101)
total sum of ascii values of char in string t is 495 that strore in sum1=495
the difference between sum1-sum is dif=495-394=>101 that ascii value of "e" but it is in integer data type
we need string/char data type so we need to data typecasting
This problem focuses on identifying the extra character added to string `t`, which is generated by shuffling the characters of string `s` and appending one additional character. The solution is based on the ASCII values of characters, where each character is mapped to a unique integer between 97 (`a`) and 122 (`z`). The approach involves summing up the ASCII values of all characters in both strings and using the difference between these sums to find the extra character. First, we calculate the total ASCII value of all characters in string `s` and store it in a variable `sum`. Similarly, we calculate the total ASCII value of all characters in string `t` and store it in another variable `sum1`. Since `t` contains all the characters of `s` and one additional character, the difference between `sum1` and `sum` gives us the ASCII value of the extra character. For example, if `s = "abcd"` and `t = "abcde"`, the sum of ASCII values of `s` is \(97 + 98 + 99 + 100 = 394\), and the sum of ASCII values of `t` is (97 + 98 + 99 + 100 + 101 = 495). The difference, \(495 - 394 = 101\), corresponds to the ASCII value of the extra character `e`. Finally, we convert this integer value back to a character using typecasting in C++ to return the result. This method is efficient with a time complexity of \(O(n + m)\), where \(n\) and \(m\) are the lengths of `s` and `t`, respectively, and a space complexity of \(O(1)\), as no additional data structures are used. This approach ensures accurate results by leveraging the properties of ASCII values and typecasting.
this is the code in C++:
0 Comments