June 3rd 2023

Valid Anagram — Typescript

Problem Description permalink

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

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true
Example 2:

Input: s = "rat", t = "car"
Output: false

Solution permalink

// Util functions
function expect(description: string, test: boolean) {
if (test) {
console.log(`${description}`)
} else {
console.log(`${description}`)
}
}

function isAnagram(s: string, t: string): boolean {
if (s.length !== t.length) {
return false
}

return s.split("").sort().join("") == t.split("").sort().join("")
};

expect("car / library aren't anagrams", !isAnagram("car", "library"))
expect("anagram / nagaram are anagrams", isAnagram("anagram", "nagaram"))
expect("rat / car aren't anagrams", !isAnagram("rat", "car"))

Discussion permalink

This solution was informed by yesterday's problem on palindromes. I didn't get fancy and just did a quick string operation.