VALID ANAGRAM

Valid Anagram – Frequency Count Approach

Introduction

An anagram is a word or phrase formed by rearranging the letters of another word using all the original letters exactly once.

In this problem, we are given two strings and need to check whether one is an anagram of the other.

Problem Statement

Given two strings s and t, return:

  • true if t is an anagram of s

  • false otherwise

Example

Input:

s = "anagram"
t = "nagaram"

Output:

true

Solution Code

class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length())
            return false;

        int[] arr = new int[26];

        for (int i = 0; i < s.length(); i++) {
            arr[s.charAt(i) - 'a']++;
            arr[t.charAt(i) - 'a']--;
        }

        for (int check : arr) {
            if (check != 0)
                return false;
        }

        return true;
    }
}

Approach Used: Frequency Counting

Idea

If two strings are anagrams:

  • They must have the same characters

  • Each character must appear the same number of times

How It Works

  1. Check lengths:

    • If lengths are different = return false

  2. Create an array of size 26:

    • Each index represents a letter (a–z)

  3. Traverse both strings:

    • Increment count for characters in s

    • Decrement count for characters in t

  4. Check the array:

    • If all values are 0 = strings are anagrams

    • Otherwise = not anagrams

Why This Approach Was Chosen

  • Very efficient (single traversal)

  • No need for sorting

  • Uses fixed-size array = constant space

  • Faster than comparing sorted strings

Alternative Approaches

  • Sorting both strings

    sort(s) == sort(t)
    

     Time Complexity: O(n log n)

  • Using HashMap
     Works for all characters
     Slightly more space

Why frequency array?
Because input contains only lowercase letters → most efficient choice

Time and Space Complexity

  • Time Complexity: O(n)

  • Space Complexity: O(1) (fixed array of size 26)

Follow-Up: Unicode Characters

If the strings contain Unicode characters:

  • We cannot use a fixed array of size 26

Modified Approach:

  • Use a HashMap

Map<Character, Integer> map = new HashMap<>();

Why?

  • Unicode has a large range of characters

  • HashMap handles dynamic character sets

Important Observation

  • Incrementing and decrementing in the same loop reduces work

  • Final check ensures all counts balance to zero

Conclusion

The frequency count approach is an efficient and elegant way to check for anagrams. It avoids sorting and works in linear time, making it ideal for large inputs. For extended character sets like Unicode, the approach can be adapted using a HashMap.


Comments

Popular posts from this blog

THE DELIVERY MAN

EC2 LAUNCHING

SORT A LINKED LIST USING MERGE SORT