Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between two strings JavaScript
We are given two strings, say s and t. String t is generated by random shuffling string s and then add one more letter at a random position.
We are required to write a JavaScript function that takes both these strings and returns the letter that was added to t.
For example −
If the input strings are −
const s = "abcd", t = "abcde";
Then the output should be −
const output = "e";
because 'e' is the letter that was added.
Method 1: Using XOR Operation
XOR operation helps find the difference because when we XOR all characters from both strings, identical characters cancel out, leaving only the added character.
const s = "abcd", t = "abcde";
const findTheDifference = (s, t) => {
let result = 0;
// XOR all characters in string s
for (let i = 0; i
e
Method 2: Using Character Count
Count characters in both strings and find which character has different count.
const s = "abcd", t = "abcde";
const findTheDifferenceCount = (s, t) => {
const charCount = {};
// Count characters in string s
for (let char of s) {
charCount[char] = (charCount[char] || 0) + 1;
}
// Check characters in string t
for (let char of t) {
if (!charCount[char]) {
return char; // Found the extra character
}
charCount[char]--;
}
};
console.log(findTheDifferenceCount(s, t));
e
Method 3: Using Sum of Character Codes
Calculate the sum of character codes for both strings. The difference gives us the added character.
const s = "abcd", t = "abcde";
const findTheDifferenceSum = (s, t) => {
let sumS = 0, sumT = 0;
for (let i = 0; i
e
Comparison
| Method | Time Complexity | Space Complexity | Performance |
|---|---|---|---|
| XOR Operation | O(n) | O(1) | Best |
| Character Count | O(n) | O(k) - k unique chars | Good |
| Sum Method | O(n) | O(1) | Good |
Conclusion
The XOR method is most efficient as it uses constant space and leverages the mathematical property that identical values cancel out. All three methods work correctly, but XOR is preferred for optimal performance.
