albertonline· portal
blind75

Valid Anagram: Checking Character Arrangements

Jan 14, 2024 · Solving the Valid Anagram problem to determine if two strings are anagrams, meaning they contain the same characters in a different order.

The "Valid Anagram" problem involves determining whether two strings are anagrams of each other, meaning they are made of the same characters, just in a different order.

Problem Statement

Given two strings s and t, write a function to determine if t is an anagram of s.

Example

  • Input: s = "anagram", t = "nagaram"
  • Output: true

Solution Approach - Character Counting (javascript)

function isAnagram(s, t) {
  if (s.length !== t.length) return false;

  let count = {};
  for (let char of s) {
    count[char] = (count[char] || 0) + 1;
  }

  for (let char of t) {
    if (!count[char]) return false;
    count[char]--;
  }

  return true;
}

Breaking Down the Solution


  • Length Check: First, check if s and t are of the same length. If not, they can't be anagrams.
  • Count Characters in s: Use a map to count the occurrences of each character in s.
  • Verify Characters in t: Iterate over t and decrease the count for each character. If a character in t isn't in s or the count goes below zero, t is not an anagram of s.

Solution in TypeScript

function isAnagram(s: string, t: string): boolean {
  if (s.length !== t.length) {
    return false;
  }

  const count: Record<string, number> = {};
  for (const char of s) {
    count[char] = (count[char] || 0) + 1;
  }

  for (const char of t) {
    if (!count[char]) {
      return false;
    }
    count[char]--;
  }

  return true;
}

In this TypeScript solution:

  • The function isAnagram takes two strings, s and t, and checks if they are anagrams.
  • It first compares the lengths of s and t. If they are different, the function returns false immediately.
  • A record count is used to count the occurrences of each character in s.
  • Then, the function iterates through t, decrementing the count for each character. If a character in t is not in s or the count drops below zero, t is not an anagram of s.
  • If all character counts are balanced, the function returns true.

This implementation effectively checks whether two strings are anagrams by comparing the frequency of each character in both strings.

Conclusion


The Valid Anagram problem is a fundamental exercise in string manipulation and character counting. It's a simple yet effective way to understand the importance of character frequency and order in strings.

Comments (0)

Stub comments live in your browser only (localStorage). No server round-trip yet.

No comments yet. Be the first.