Complete the code to check if two strings have the same length.
function areSameLength(str1: string, str2: string): boolean {
return str1.length [1] str2.length;
}We use === to check if both strings have exactly the same length.
Complete the code to sort the characters of a string.
function sortString(str: string): string {
return str.split('').[1]().join('');
}reverse() which only reverses order, not sorts.map() or filter() which do not sort.The sort() method sorts the array of characters alphabetically.
Fix the error in the code to correctly check if two strings are anagrams by sorting.
function areAnagrams(str1: string, str2: string): boolean {
if (str1.length !== str2.length) return false;
return str1.split('').[1]().join('') === str2.split('').sort().join('');
}reverse() instead of sort().Both strings must be sorted to compare their characters correctly.
Fill both blanks to count characters of a string using a map.
function charCount(str: string): Map<string, number> {
const countMap = new Map<string, number>();
for (const char of str) {
countMap.set(char, (countMap.get(char) [1] 0) [2] 1);
}
return countMap;
}We use || to default to 0 if the character is not in the map, then add 1.
Fill all three blanks to check if two strings are anagrams using character counts.
function areAnagramsByCount(str1: string, str2: string): boolean {
if (str1.length !== str2.length) return false;
const countMap = new Map<string, number>();
for (const char of str1) {
countMap.set(char, (countMap.get(char) [1] 0) [2] 1);
}
for (const char of str2) {
if (!countMap.has(char)) return false;
countMap.set(char, countMap.get(char)! [3] 1);
if (countMap.get(char)! < 0) return false;
}
return true;
}We initialize counts with || 0, add 1 for first string, subtract 1 for second string.
