Bird
Raised Fist0
DSA Javascriptprogramming~10 mins

Anagram Check Techniques in DSA Javascript - Execution Trace

Choose your learning style10 modes available
Concept Flow - Anagram Check Techniques
Input two strings
↓
Normalize strings: lower case, remove spaces
↓
Choose technique
↓
Sort & Compare
↓
Are they equal?
Yes→Anagrams
No↓
Not Anagrams
Start with two strings, normalize them, then use one of three techniques to check if they are anagrams by comparing sorted strings, character counts, or frequency maps.
Execution Sample
DSA Javascript
function areAnagrams(s1, s2) {
  const normalize = str => str.toLowerCase().replace(/\s+/g, '');
  s1 = normalize(s1);
  s2 = normalize(s2);
  if (s1.length !== s2.length) return false;
  return s1.split('').sort().join('') === s2.split('').sort().join('');
}
This code normalizes two strings and checks if their sorted characters are equal to determine if they are anagrams.
Execution Table
StepOperationString 1 StateString 2 StateComparison ResultConclusion
1Input strings"Listen""Silent"N/AN/A
2Normalize strings"listen""silent"N/AN/A
3Check length equality6 chars6 charsEqualContinue
4Sort characters"eilnst""eilnst"EqualAnagrams
5Return resultN/AN/AN/ATrue
💡 Strings sorted and compared; they match, so they are anagrams.
Variable Tracker
VariableStartAfter NormalizeAfter SortFinal
s1"Listen""listen""eilnst""eilnst"
s2"Silent""silent""eilnst""eilnst"
Key Moments - 3 Insights
Why do we normalize strings before checking?
Normalization (lowercase and removing spaces) ensures that differences in case or spaces do not affect the anagram check, as shown in step 2 of the execution_table.
Why compare lengths before sorting?
If lengths differ (step 3), strings cannot be anagrams, so we can stop early without sorting, saving time.
Why does sorting help check anagrams?
Sorting rearranges characters in order, so if two strings have the same sorted form (step 4), they contain the same characters in the same counts.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state of s1 after normalization?
A"eilnst"
B"Listen"
C"listen"
D"Silent"
💡 Hint
Check the 'String 1 State' column at step 2 in the execution_table.
At which step does the code decide the strings are anagrams?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Look for the step where sorted strings are compared and found equal.
If the strings had different lengths, what would happen?
AThe code would continue to sort and compare.
BThe code would return false immediately.
CThe code would normalize again.
DThe code would throw an error.
💡 Hint
Refer to step 3 in the execution_table where length check happens.
Concept Snapshot
Anagram Check Techniques:
- Normalize strings (lowercase, remove spaces)
- Technique 1: Sort both strings and compare
- Technique 2: Count characters and compare counts
- Technique 3: Use frequency maps to compare
- Early length check saves time
- Equal sorted strings mean anagrams
Full Transcript
This lesson shows how to check if two strings are anagrams. First, we normalize the strings by making them lowercase and removing spaces. Then, we check if their lengths are equal. If not, they cannot be anagrams. If lengths match, we use one technique: sorting both strings and comparing the sorted results. If the sorted strings are equal, the original strings are anagrams. This method works because sorting arranges characters in order, so equal sorted strings mean the same characters with the same counts. We tracked the strings through each step, showing their states after normalization and sorting. Key points include why normalization is needed, why length check is important, and how sorting helps. The quiz asks about these steps to reinforce understanding.

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