Bird
Raised Fist0
DSA Javascriptprogramming

Anagram Check Techniques in DSA Javascript

Choose your learning style10 modes available
Mental Model
Two words are anagrams if they have the same letters in the same amounts, just mixed differently.
Analogy: Imagine two bags of colored beads. If both bags have the exact same colors and number of beads, just jumbled differently, they are anagrams.
word1: c -> a -> t -> null
word2: t -> a -> c -> null

Both have letters c, a, t but in different order.
Dry Run Walkthrough
Input: Check if 'listen' and 'silent' are anagrams
Goal: Determine if both words have the same letters with the same frequency
Step 1: Convert both words to arrays of letters
listen: [l, i, s, t, e, n]
silent: [s, i, l, e, n, t]
Why: We need to compare letters individually
Step 2: Sort both arrays alphabetically
listen sorted: [e, i, l, n, s, t]
silent sorted: [e, i, l, n, s, t]
Why: Sorting puts letters in order to easily compare
Step 3: Compare sorted arrays letter by letter
All letters match in order: e == e, i == i, l == l, n == n, s == s, t == t
Why: Matching sorted letters means words are anagrams
Result:
listen sorted: e -> i -> l -> n -> s -> t -> null
silent sorted: e -> i -> l -> n -> s -> t -> null
Answer: true (they are anagrams)
Annotated Code
DSA Javascript
class AnagramChecker {
  static areAnagrams(word1, word2) {
    if (word1.length !== word2.length) return false; // different lengths can't be anagrams
    const sorted1 = [...word1.toLowerCase()].sort(); // sort letters of first word
    const sorted2 = [...word2.toLowerCase()].sort(); // sort letters of second word
    for (let i = 0; i < sorted1.length; i++) {
      if (sorted1[i] !== sorted2[i]) return false; // mismatch found
    }
    return true; // all letters match
  }
}

// Driver code
const word1 = 'listen';
const word2 = 'silent';
const result = AnagramChecker.areAnagrams(word1, word2);
console.log(result);
if (word1.length !== word2.length) return false;
Check if lengths differ -- quick elimination
const sorted1 = [...word1.toLowerCase()].sort();
Sort letters of first word to prepare for comparison
const sorted2 = [...word2.toLowerCase()].sort();
Sort letters of second word similarly
for (let i = 0; i < sorted1.length; i++) { if (sorted1[i] !== sorted2[i]) return false; }
Compare each letter in order; return false if any mismatch
return true;
If all letters match, words are anagrams
OutputSuccess
true
Complexity Analysis
Time: O(n log n) because sorting both words takes that time where n is word length
Space: O(n) because we create sorted arrays of letters
vs Alternative: Using sorting is simpler but slower than counting letters with a hash map which can be O(n)
Edge Cases
Empty strings
Returns true because two empty words trivially have the same letters
DSA Javascript
if (word1.length !== word2.length) return false;
Different lengths
Returns false immediately since lengths differ
DSA Javascript
if (word1.length !== word2.length) return false;
Same letters but different orders (e.g. 'aabb' and 'abab')
Returns true because letters and counts match
DSA Javascript
for (let i = 0; i < sorted1.length; i++) { if (sorted1[i] !== sorted2[i]) return false; }
When to Use This Pattern
When you need to check if two words have the same letters in any order, use the anagram check pattern by sorting or counting letters.
Common Mistakes
Mistake: Comparing words directly without sorting or counting letters
Fix: Sort both words or count letters before comparing
Mistake: Ignoring letter case differences
Fix: Convert both words to the same case (e.g., lowercase) before checking
Summary
Checks if two words have the same letters in the same amounts, regardless of order.
Use when you want to know if two strings are anagrams of each other.
Sorting letters or counting their frequency lets you compare words easily.

Practice

(1/5)
1. What does it mean if two strings are anagrams of each other?
easy
A. They have the same length but different characters
B. They start with the same letter
C. They contain the same characters in any order
D. They have no characters in common

Solution

  1. Step 1: Understand the definition of anagrams

    Anagrams are words or phrases made by rearranging the letters of another, so they must have the same characters.
  2. Step 2: Compare the character sets

    If two strings have exactly the same characters, just in different orders, they are anagrams.
  3. Final Answer:

    They contain the same characters in any order -> Option C
  4. Quick Check:

    Anagrams = same characters [OK]
Hint: Check if sorted strings match to confirm anagrams [OK]
Common Mistakes:
  • Thinking same length means anagrams
  • Assuming same first letter means anagrams
  • Ignoring character counts
2. Which of the following JavaScript code snippets correctly checks if two strings are anagrams by sorting?
easy
A. const areAnagrams = (a, b) => a.split('').sort() === b.split('').sort();
B. const areAnagrams = (a, b) => a.split().sort().join() === b.split().sort().join();
C. const areAnagrams = (a, b) => a.sort() === b.sort();
D. const areAnagrams = (a, b) => a.split('').sort().join('') === b.split('').sort().join('');

Solution

  1. Step 1: Understand string and array methods

    Strings need to be split into arrays to sort, then joined back to strings for comparison.
  2. Step 2: Check each option's correctness

    const areAnagrams = (a, b) => a.split('').sort().join('') === b.split('').sort().join(''); correctly splits, sorts, and joins both strings before comparing. const areAnagrams = (a, b) => a.split('').sort() === b.split('').sort(); compares arrays directly (wrong). const areAnagrams = (a, b) => a.sort() === b.sort(); tries to sort strings directly (invalid). const areAnagrams = (a, b) => a.split().sort().join() === b.split().sort().join(); uses split() without argument and join() without argument, which is incorrect.
  3. Final Answer:

    const areAnagrams = (a, b) => a.split('').sort().join('') === b.split('').sort().join(''); -> Option D
  4. Quick Check:

    Split + sort + join = correct syntax [OK]
Hint: Remember to join sorted arrays before comparing strings [OK]
Common Mistakes:
  • Comparing arrays directly with ===
  • Not joining arrays back to strings
  • Using split() without arguments
3. What will be the output of the following code?
function isAnagram(s1, s2) {
  if (s1.length !== s2.length) return false;
  const count = {};
  for (const char of s1) {
    count[char] = (count[char] || 0) + 1;
  }
  for (const char of s2) {
    if (!count[char]) return false;
    count[char]--;
  }
  return true;
}
console.log(isAnagram('listen', 'silent'));
console.log(isAnagram('hello', 'bello'));
medium
A. true false
B. false true
C. true true
D. false false

Solution

  1. Step 1: Analyze the first call isAnagram('listen', 'silent')

    Both strings have same length. Counting characters in 'listen' and subtracting counts for 'silent' matches perfectly, so returns true.
  2. Step 2: Analyze the second call isAnagram('hello', 'bello')

    Strings have same length but 'hello' has 'h' which 'bello' does not. The count check fails and returns false.
  3. Final Answer:

    true false -> Option A
  4. Quick Check:

    Matching counts = true, mismatch = false [OK]
Hint: Count chars in first, subtract in second, check zero [OK]
Common Mistakes:
  • Ignoring length check
  • Not decrementing counts properly
  • Returning true too early
4. The following code is intended to check if two strings are anagrams. What is the bug?
function checkAnagram(a, b) {
  const map = new Map();
  for (let i = 0; i < a.length; i++) {
    map.set(a[i], (map.get(a[i]) || 0) + 1);
    map.set(b[i], (map.get(b[i]) || 0) - 1);
  }
  for (const val of map.values()) {
    if (val !== 0) return false;
  }
  return true;
}
medium
A. It incorrectly updates counts for both strings in the same loop
B. It does not check string lengths before processing
C. It uses Map instead of a plain object which is invalid
D. It forgets to return true at the end

Solution

  1. Step 1: Identify missing length check

    The code lacks an initial check to ensure both strings have the same length.
  2. Step 2: Understand the impact of missing length check

    If `a.length < b.length`, the loop only iterates `a.length` times, incrementing counts for all of `a` but decrementing only the first `a.length` characters of `b`. Extra characters in `b` are ignored, potentially returning `true` incorrectly. Example: `checkAnagram('ab', 'abc')` balances 'a' and 'b' but ignores 'c', wrongly returns `true`. If `a` longer, it may detect mismatch via extra increments or `undefined` key.
  3. Final Answer:

    It does not check string lengths before processing -> Option B
  4. Quick Check:

    Missing length check = false positives [OK]
Hint: Check lengths first, then count characters [OK]
Common Mistakes:
  • Updating counts for both strings simultaneously
  • Assuming Map is invalid in JS
  • Missing length check
5. You want to check if two strings are anagrams ignoring spaces and case. Which approach correctly implements this in JavaScript?
function isAnagramAdvanced(s1, s2) {
  // Fill in the blanks
}
hard
A. Normalize strings by removing spaces and lowercasing, then compare sorted characters
B. Compare lengths directly after trimming spaces only
C. Use a Map to count characters but ignore case and spaces only in one string
D. Check if s1 includes s2 ignoring case and spaces

Solution

  1. Step 1: Normalize both strings

    Remove all spaces and convert both strings to lowercase to ignore case and spaces.
  2. Step 2: Sort and compare normalized strings

    Sort the characters of both normalized strings and compare them to check if they are anagrams.
  3. Final Answer:

    Normalize strings by removing spaces and lowercasing, then compare sorted characters -> Option A
  4. Quick Check:

    Normalize + sort + compare = correct approach [OK]
Hint: Clean strings first, then sort and compare [OK]
Common Mistakes:
  • Ignoring spaces in one string only
  • Comparing lengths without normalization
  • Using includes() which is incorrect for anagrams
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard