DEV Community

Jarvish John
Jarvish John

Posted on • Edited on

CA 14 - Valid Anagram

Problem Statement

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

An anagram means both strings contain the same characters with the same frequency, just arranged differently.

Examples:

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

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

Here’s your version rewritten in your usual tone πŸ‘‡


Solution:
For this problem, my goal was to understand how character frequency works in strings and compare two strings efficiently without overcomplicating things. I wanted to keep the logic simple and readable, especially since this is a basic concept.

I used a sorting-based approach because it’s straightforward and beginner-friendly. The idea is to sort both strings and then compare them. If both sorted results are the same, it means both strings have the same characters, so they are anagrams. Otherwise, they are not.

s = "anagram"
t = "nagaram"

print(sorted(s) == sorted(t))
Enter fullscreen mode Exit fullscreen mode

Here, sorting rearranges the characters in both strings. If the sorted versions match, it confirms that both strings contain the same characters with the same frequency, so they are anagrams.
m

Top comments (0)