Check for Anagrams

Hero Image

Problem Overview

The "Valid Anagram" problem is a popular coding challenge found on LeetCode, typically categorized under string manipulation problems. The problem requires determining whether two given strings are anagrams of each other. An anagram of a string is formed by rearranging the characters of the string to produce a new string.

Problem Statement:

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Constraints:

  • The strings consist of lowercase English letters.
  • The lengths of the strings are not more than 10^5.

Leetcode Problem - Valid Anagram

Understanding the Problem

An anagram requires that both strings have the same frequency of each character. For instance, s = "anagram" and t = "nagaram" are anagrams because both strings have identical character occurrences when sorted or counted by the frequency of characters.

Examples:

  • Example 1:

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

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

Key DSA Concepts and Theory

Strings

A string is a data structure that represents a sequence of characters. In many programming languages, strings are immutable, meaning that once a string is created, it cannot be changed.

Hash Table (or Hash Map)

A hash table is a data structure that implements an associative array, a structure that can map keys to values. It uses a hash function to compute an index, also called a hash code, into an array of buckets or slots, from which the desired value can be found.

Sorting

Sorting is a common operation in programming. It's a process of arranging the elements of a collection in a certain order. Sorting the strings and comparing is a simple method to check if two strings are anagrams.

Solution Approach

Approach 1: Using Sorting

  1. Convert both strings into character arrays.
  2. Sort both character arrays.
  3. Compare the sorted arrays; if they are equal, the strings are anagrams.

C++ Code:

#include <algorithm>
#include <string>

bool isAnagram(std::string s, std::string t) {
    if (s.length() != t.length()) return false;
    std::sort(s.begin(), s.end());
    std::sort(t.begin(), t.end());
    return s == t;
}

Java Code:

import java.util.Arrays;

public class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;
        char[] sArray = s.toCharArray();
        char[] tArray = t.toCharArray();
        Arrays.sort(sArray);
        Arrays.sort(tArray);
        return Arrays.equals(sArray, tArray);
    }
}

Approach 2: Using Hash Table (Character Count)

  1. Create an array of 26 elements (since we are dealing with lowercase English letters) to count the frequency of each character.
  2. Increment the count for each character in s.
  3. Decrement the count for each character in t.
  4. If all elements in the count array are zero, the strings are anagrams.

C++ Code:

#include <string>
#include <vector>

bool isAnagram(std::string s, std::string t) {
    if (s.length() != t.length()) return false;
    std::vector<int> count(26, 0);
    for (char c: s) count[c - 'a']++;
    for (char c: t) count[c - 'a']--;
    for (int i: count) {
        if (i != 0) return false;
    }
    return true;
}

Java Code:

public class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;
        int[] count = new int[26];
        for (char c : s.toCharArray()) count[c - 'a']++;
        for (char c : t.toCharArray()) count[c - 'a']--;
        for (int i : count) {
            if (i != 0) return false;
        }
        return true;
    }
}

Time and Space Complexity Analysis

Sorting Approach:

  • Time Complexity: O(n log n) for sorting the strings s and t.
  • Space Complexity: O(1) if sorting in place, otherwise O(n) for additional space used by sorted arrays.

Hash Table (Character Count) Approach:

  • Time Complexity: O(n), where n is the length of the strings s and t.
  • Space Complexity: O(1) since the auxiliary space used (character count) does not depend on the input size.

Common Mistakes to Avoid

  • Not checking if the lengths of the strings s and t are equal before performing further operations can lead to incorrect assumptions.
  • Mistakenly using a case-sensitive comparison if only lowercase letters are involved.

Similar Problems on LeetCode

  • 438. Find All Anagrams in a String
  • 49. Group Anagrams

Additional Resources and References

In conclusion, understanding how to manipulate strings and use efficient data structures like hash tables can significantly optimize solutions to problems like "Valid Anagram". The choice between sorting and hash table approaches often depends on constraints and performance requirements.