19 March 2024
Easy
242. Valid Anagram
Link: https://leetcode.com/problems/valid-anagram
Description: We need to check if two strings are anagrams of each other.
First solution:
Firstly check length of both strings. If they are not equal, return false. Then convert second string to array and iterate over first string. If letter is found in array, remove it from array. If array is empty, return true.
var isAnagram = function (s, t) {
if (s.length !== t.length) {
return false
}
const tArray = t.split('')
for (const letter of s) {
const index = tArray.indexOf(letter)
if (index >= 0) {
tArray.splice(index, 1)
}
}
return tArray.length === 0
}
Second solution:
Firstly check length of both strings. If they are not equal, return false. Then convert both strings to arrays, sort them and compare each letter. If any letter is different, return false. If no letter is different, return true.
var isAnagram = function (s, t) {
if (s.length !== t.length) {
return false
}
const sSorted = s.split('').sort()
const tSorted = t.split('').sort()
for (let i = 0; i <= sSorted.length; i++) {
if (sSorted[i] !== tSorted[i]) {
return false
}
}
return true
}
Second solution is faster than first one.