DEV Community

Sruthika Ramachandran
Sruthika Ramachandran

Posted on

Valid Anagram

Introduction

Strings are one of the most important topics in programming.
A common problem is checking whether two strings are anagrams, which means they contain the same characters in a different order.

Problem Statement

Given two strings s and t, return:

  • true if t is an anagram of s
  • false otherwise

Note:

  • Both strings contain only lowercase English letters

Examples

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

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

Intuition

  • If two strings are anagrams:

    • They must have the same characters
    • With the same frequency

Approach (Frequency Count)

Instead of sorting, we count occurrences of each character.

Algorithm Steps

  • If lengths are different → return false
  • Create a frequency array of size 26
  • Traverse both strings:

    • Increment count for s[i]
    • Decrement count for t[i]
  • If all values are 0 → anagram

Code (Python)

def is_anagram(s, t):
    if len(s) != len(t):
        return False

    count = [0] * 26

    for i in range(len(s)):
        count[ord(s[i]) - ord('a')] += 1
        count[ord(t[i]) - ord('a')] -= 1

    return all(c == 0 for c in count)

Enter fullscreen mode Exit fullscreen mode

Step-by-Step Explanation

For "anagram" and "nagaram":

  • Count characters in both strings
  • Each increment cancels with decrement
  • Final array → all zeros → valid anagram

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1) (fixed 26 letters)

Conclusion

Checking for anagrams is a fundamental string problem that teaches frequency counting and efficient comparison techniques.

Top comments (0)