Leetcode - Valid Anagram

February 6th, 2024
Description

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

Constraints:

  • 1 <= s.length, t.length <= 5 * 10^4
  • s and t consist of lowercase English letters.
Solution

For this problem, I noted a few things:

  1. Two strings of different lengths can not be anagrams. I can immediately rule out some anagrams by comparing the lengths of s and t.
  2. I can track the differences between the two strings without actually comparing them. All I would need to do is track each unique letter in object letters. I would increment the number value assigned to the letter by 1 if it's from string s, and decrement it by 1 if it's from string t. If by the end any letter in object letters has any value other than 0, that means there is an inconsistency in the amount of times the letter appears in each string.
function isAnagram(s: string, t: string): boolean {
    if (s.length != t.length) {
        return false;
    }

    const letters = {};

    for (let i = 0; i < s.length; i++) {
        if (letters[s[i]]) {
            letters[s[i]]++;
        } else {
            letters[s[i]] = 1;
        }

        if (letters[t[i]]) {
            letters[t[i]]--;
        } else {
            letters[t[i]] = -1;
        }
    }

    for (const letter in letters) {
        if (letters[letter] != 0) {
            return false;
        }
    }

    return true;
};

This code has a runtime of 57 ms and a memory usage of 53.41 MB.