Skip to content

242 Valid Anagram ✅

Leetcode

::: tip Key points 💡

  • Character count map Dictionary() :::

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

Example 1:

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

Example 2:

Input: s = "rat", t = "car"
Output: false

Note: You may assume the string contains only lowercase alphabets.

Follow up: What if the inputs contain unicode characters? How would you adapt your solution to such case?

C# Solution

using System;
using System.Collections.Generic;
using System.Linq;

namespace Algorithms.Simple
{
  public class Anagram
  {
    public static bool IsAnagram(string inputString1, string inputString2)
    {
      var charCountMap = new Dictionary<char, int>();

      foreach (var character in inputString1)
      {
        charCountMap[character] = charCountMap.ContainsKey(character) ? charCountMap[character] + 1 : 1;
      }

      foreach (var character in inputString2)
      {
        if (!charCountMap.ContainsKey(character)) return false;

        charCountMap[character] = charCountMap[character] - 1;
      }

      return charCountMap.Where(kvp => kvp.Value > 0).ToList().Count == 0;
    }
  }
}

C# Tests

using Algorithms.Simple;
using Xunit;

namespace AlgorithmTests.Simple
{
  public class AnagramTests
  {
    [Fact]
    public void ValidAnagram()
    {
      Assert.True(Anagram.IsAnagram("anagram", "nagaram"));
    }

    [Fact]
    public void InvalidAnagram()
    {
      Assert.False(Anagram.IsAnagram("car", "jar"));
    }
  }
}