Fetching latest headlines…
Valid Anagram
NORTH AMERICA
πŸ‡ΊπŸ‡Έ United Statesβ€’March 22, 2026

Valid Anagram

2 views0 likes0 comments
Originally published byDev.to

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

Comments (0)

Sign in to join the discussion

Be the first to comment!