DEV Community

Dharani
Dharani

Posted on

Valid Anagram

Introduction

A valid anagram problem is a common question in programming interviews. It helps us understand strings, sorting, and frequency counting.


Problem Statement

Given two strings s and t, determine if t is an anagram of s.

An anagram means both strings contain the same characters with the same frequency, but possibly in a different order.


Approach 1: Sorting Method

  1. Sort both strings
  2. Compare the sorted results
  3. If equal → valid anagram

Python Code (Sorting)


python
def isAnagram(s, t):
    return sorted(s) == sorted(t)

# Example
print(isAnagram("listen", "silent"))

## Approach 2: Frequency Count
1. count characters in both strings
2.compare counts

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

    count = {}

    for char in s:
        count[char] = count.get(char, 0) + 1

    for char in t:
        if char not in count or count[char] == 0:
            return False
        count[char] -= 1

    return True

## Example
print(isAnagram("listen", "silent"))

## Input
s = "listen"
t = "silent"

## output
True
Enter fullscreen mode Exit fullscreen mode

Top comments (0)