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
Selected Reading
Finding and returning uncommon characters between two strings in JavaScript
Problem
We are required to write a JavaScript function that takes in two strings. Our function should return a new string of characters which is not common to both the strings.
Example
Following is the code −
const str1 = "xyab";
const str2 = "xzca";
const findUncommon = (str1 = '', str2 = '') => {
const res = [];
for (let i = 0; i < str1.length; i++){
if (!(str2.includes(str1[i]))){
res.push(str1[i])
}
}
for (let i = 0; i < str2.length; i++){
if (!(str1.includes(str2[i]))){
res.push(str2[i])
}
}
return res.join("");
};
console.log(findUncommon(str1, str2));
Output
ybzc
How It Works
The function compares each character from both strings:
- First loop: Finds characters in
str1that don't exist instr2 - Second loop: Finds characters in
str2that don't exist instr1 - Returns concatenated uncommon characters
Alternative Approach Using Set
A more efficient approach using Set for faster lookups:
const findUncommonWithSet = (str1 = '', str2 = '') => {
const set1 = new Set(str1);
const set2 = new Set(str2);
let result = '';
// Characters in str1 but not in str2
for (let char of str1) {
if (!set2.has(char)) {
result += char;
}
}
// Characters in str2 but not in str1
for (let char of str2) {
if (!set1.has(char)) {
result += char;
}
}
return result;
};
console.log(findUncommonWithSet("hello", "world"));
console.log(findUncommonWithSet("abc", "def"));
helwrd abcdef
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| includes() method | O(n*m) | O(1) | Short strings |
| Set approach | O(n+m) | O(n+m) | Longer strings |
Conclusion
Both approaches find uncommon characters between strings. The Set method is more efficient for larger strings, while the includes() method is simpler for basic use cases.
Advertisements
