Skip to content Skip to sidebar Skip to footer

How Can I Compare Two Shuffled Strings?

I have the following two strings: var str1 = 'hello'; var str2 = 'ehlol'; How can I check whether both strings contain the same characters?

Solution 1:

May not be very optimal, but you can simply do

str1.split("").sort().join() == str2.split("").sort().join(); //outputs true

Another suggested approach in one the comments (for optimization in case string length is quite big)

str1.length===str2.length && str1.split("").sort().join() == str2.split("").sort().join(); //firstcheck the length to quickly rule outincaseof obvious non-matches

Solution 2:

One of the recommended ways to do it is using a hash table: count how many times each character appears. Note that this works best if your characters are ASCII.

The complexity of this algorithm is O(M+N+sigma) where M, N are the lengths of the strings and sigma is the number of distinct letters. The complexity of the accepted solution is higher because of the sorting, which is usually done in O(N*logN), but still a good one if your strings are short. If your strings have hundreds of thousands of characters, then this is the way to go. The drawback of using hash tables is that the memory usage is higher than the solution that uses sorting.

function sameLetters(str1, str2){
  var hash = {};

  var len1 = str1.length;
  var len2 = str2.length;

  // Strings with different lengths can't contain the same lettersif(len1 !== len2) returnfalse;

  // Count how many times each character appears in str1for(var i = 0; i < len1; ++i) {
    var c =  str1[i];
    if(typeof hash[c] !== 'undefined') hash[c]++;
    else hash[c] = 1;
  }

  // Make sure each character appearing in str2 was found in str1for(var i = 0; i < len2; ++i) {
    var c =  str2[i];
    if(typeof hash[c] === 'undefined') returnfalse;
    if(hash[c] === 0) returnfalse;
    hash[c]--;
  }

  // Make sure no letters are leftfor(var c in hash) {
    if(hash[c]) returnfalse;
  }    

  returntrue;
}

You can then call the function like this (play with it in the browser console):

sameLetters("hello", "ehlol"); //true
sameLetters("hello", "ehllol"); //false

Solution 3:

You can use a function for this purpose like sameChars function here-

functionmyFunction()
{
    var input_1 = document.getElementById('input_1').value;
    var input_2 = document.getElementById('input_2').value;
    var result = sameChars(input_1,input_2);
    document.getElementById("demo").innerHTML = result;
}

functionsameChars(firstStr, secondStr)
{
    var first = firstStr.split('').sort().join('');
    var second = secondStr.split('').sort().join('');
    return first.localeCompare(second)==0;
}
<inputtype="text"maxlength="512"id="input_1"/><inputtype="text"maxlength="512"id="input_2"/><buttononclick="myFunction()">Check If Shuffled</button><pid="demo"></p>

Solution 4:

Here's a modified version of Gurvinders answer.

var str1 = "hello",
    str2 = "ehlol";

// Add sort on prototype of String objectString.prototype.sort = function () {
    returnthis.split('').sort().join('');
};

// First check if length of both is samevar same = str1.length === str2.length && str1.sort() === str2.sort();
console.log('Strings are same?', same);

Solution 5:

You could possibly say this:

(a.length === b.length) &&   (a.split('').every(function(val) { return b.indexOf(val) > -1}))

And, in ES6 you could make it look as follows:

(a.length === b.length) && a.split('').every(val => { return b.indexOf(val) > -1 })

Post a Comment for "How Can I Compare Two Shuffled Strings?"