242. Valid Anagram 🎢
Difficulty: Easy - Tags: Hash Table, String, Sorting
Problem Statement 📜
Given two strings s and t, determine if t is an anagram of s. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.
Examples 🌟
🔹 Example 1:
Input:
s = "anagram", t = "nagaram"Output:
true🔹 Example 2:
Input:
s = "rat", t = "car"Output:
Constraints ⚙️
1 <= s.length, t.length <= 5 * 10^4sandtconsist of lowercase English letters.
Solution 💡
The simplest way to check if two strings are anagrams is to compare their sorted versions. Alternatively, we can use a frequency count for more efficiency.
Java Solution (Sorting Approach)
Java Solution (HashMap Approach)
Explanation of the Solution
Sorting Approach:
Convert both strings to character arrays.
Sort the arrays.
Compare the sorted arrays for equality.
HashMap Approach:
Count the frequency of each character in
susing aHashMap.For each character in
t, decrement its count in the map.If a character in
tis missing or its count goes below zero, returnfalse.
Time Complexity ⏳
Sorting Approach:
O(n log n) for sorting, where
nis the length of the strings.
HashMap Approach:
O(n) for iterating through the strings.
Space Complexity 💾
Sorting Approach:
O(n) for storing the sorted arrays.
HashMap Approach:
O(1) space for the map (since there are only 26 lowercase English letters).
You can find the full solution here.
Last updated
Was this helpful?