Ria
Ria

Reputation: 49

Anagram solution using json.stringify, is this a right approach to solve

I have sorted out two string and than used json.stringify to compare it to get Anagram. please refer below code, is this a right way to code.

function same(ar, ar1) {
  //sorting the string
  var o = ar.split("").sort();
  var o1 = ar1.split("").sort();
  //comparing two string
  if (JSON.stringify(o) == JSON.stringify(o1)) {
    return true;
  } else {
    return false;
  }
}
same("ria", "air"); //true
same("", ""); //true
same("aaz", zza); //false

Upvotes: 0

Views: 109

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370809

It'll work in most cases, but it's unnecessarily computationally expensive.

It may not work when certain non-ASCII characters are used, because .split('') will result in splitting up the character code points, eg:

console.log('𝟘'.split(''));

That's not an accurate representation of each character as an element of the array. Use Array.from instead:

console.log(Array.from('𝟘'));

After that, you can also make the algorithm less expensive by counting up the number of occurrences of each character (O(n)) rather than sorting (O(n log n)). For example:

const getCount = str => Array.from(str).reduce((counts, char) => {
  counts[char] = (counts[char] || 0) + 1;
  return counts;
}, {});

function same(ar,ar1){
  const counts1 = getCount(ar);
  const counts2 = getCount(ar1);
  const keys1 = Object.keys(counts1);
  const keys2 = Object.keys(counts2);
  if (keys1.length !== keys2.length) {
    return false;
  }
  return keys1.every(char => counts1[char] === counts2[char]);
}
console.log(same('abc', 'cba'));
console.log(same('abc', 'aba'));

Upvotes: 1

Related Questions