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 str1 that don't exist in str2
  • Second loop: Finds characters in str2 that don't exist in str1
  • 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.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements