CodingEasy Strings

Valid Anagram

Asked for all developer roles

Why they ask this: Checks counting with a hash map and comparing frequency, a pattern used in many string problems.

Problem

Given two lowercase strings a and b, return true if b is an anagram of a (it uses exactly the same letters the same number of times), otherwise false.

Example 1

text
Input:  a = "listen", b = "silent"
Output: true

Example 2

text
Input:  a = "rat", b = "car"
Output: false

Hints

    Approach

    1. If the lengths differ, return false.
    2. Count how many times each character appears in a using a map.
    3. Walk through b and decrement the count of each character. If a character is missing or its count is already zero, return false.
    4. Because the lengths are equal and no count went below zero, every count is zero, so return true.

    Sorting both strings and comparing them also works, but costs O(n log n).

    Solution

    js
    function isAnagram(a, b) {
      if (a.length !== b.length) return false;
    
      const counts = new Map();
      for (const ch of a) {
        counts.set(ch, (counts.get(ch) ?? 0) + 1);
      }
    
      for (const ch of b) {
        const remaining = counts.get(ch);
        if (!remaining) return false; // missing or already used up
        counts.set(ch, remaining - 1);
      }
    
      return true;
    }
    
    console.log(isAnagram('listen', 'silent')); // true
    console.log(isAnagram('rat', 'car'));       // false
    Time O(n) Space O(k), k = number of distinct characters

    Can you explain this in your own words?

    Back to coding practice