2023-06-17

 17 Jun 2023

Check if two Strings are Anagrammatic

Taken from LeetCode

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Solution

This is the answer I came up with:

function isAnagram(s: string, t: string): boolean {
  // An anagram isn't possible if the lengths differ
  if (s.length !== t.length) { return false }

  // Convert strings to sorted arrays
  let _s = [...s].sort()
  let _t = [...t].sort()
  
  // Stringify the arrays and compare them
  return JSON.stringify(_s) === JSON.stringify(_t)
}

Testing

Solution tested in REPL:

https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABDAzgQTAQwOYCdMC2AFCgFyIpS4xjYA0iU5l1tAlOQEZxwA2AppiQBvALAAoRIgD00xBkRCc+AshRgA5FEQAHOChQxOA5MEYALfogG0o5lIgAmMYMH64JUl4hIA6G9h2iACEALyhjP78tuZsiMKIuPxQILhIwJi8KFYAvhKeMnIAwggAbu7aLDTYDlBwFHC4UPyOirj4AJ4oBQLaAPoOEQDavqMoALq+KI1QRGw9yYh92sOjvlCT001zBQWyiADKVNUuHRZWmO2YXYpgrRBwBDqXVnb8BAVJKWmIAFIHAHkAHJTY60U5EAZxcIRf7A0GsbAQ5bzcR5cQSB5gaYCfxwbBEAqoDDKQhEABESjwhHJDHJWGwlxpbAY+yoIH4RPQDJUFPwUFpiHJEEu5JZhUQGSynMkahJ1OIlN4OnMmEF5M4+FKcDFrLkUuyXPlvPJuB4ArpdUauol7JlXm5pMVarpmE4EBt+wN9rlPLJlMwEA9dKDgbFEu9ElRQA

Copyright © Paramdeo Singh · All Rights Reserved · Built with Jekyll

This node last updated October 9, 2024 and is permanently morphing...

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems