Skip to content

Commit d835ecf

Browse files
authored
Merge pull request #5 from shreyasrajiv327/contrinution
feat: Implement solution for 242. Valid Anagram and update README
2 parents a326a8c + 986cb7a commit d835ecf

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
class Main {
5+
public boolean isAnagram(String s, String t) {
6+
if (s.length() != t.length()) {
7+
return false;
8+
}
9+
10+
Map<Character, Integer> countS = new HashMap<>();
11+
Map<Character, Integer> countT = new HashMap<>();
12+
13+
for (int i = 0; i < s.length(); i++) {
14+
char c1 = s.charAt(i);
15+
countS.put(c1, countS.getOrDefault(c1, 0) + 1);
16+
}
17+
18+
for (int i = 0; i < t.length(); i++) {
19+
char c2 = t.charAt(i);
20+
countT.put(c2, countT.getOrDefault(c2, 0) + 1);
21+
}
22+
23+
for (char c : countS.keySet()) {
24+
if (!countT.containsKey(c) || !countT.get(c).equals(countS.get(c))) {
25+
return false;
26+
}
27+
}
28+
29+
return true;
30+
}
31+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Valid Anagram
2+
Problem Name: 242. Valid Anagram
3+
4+
Approach: Using Hash Maps
5+
6+
Difficulty: Easy
7+
8+
Link: [Leetcode](https://leetcode.com/problems/valid-anagram/description/)
9+
10+
Explanation:
11+
12+
In this problem, we are given two strings, s and t. We need to determine if t is an anagram of s. An anagram is a word or phrase formed by rearranging the letters of another word or phrase, typically using all the original letters exactly once.
13+
14+
Solution Explanation
15+
16+
Check Lengths:
17+
First, check if the lengths of the two strings are equal. If not, return false immediately as they cannot be anagrams.
18+
Count Characters:
19+
20+
Use two hash maps to count the frequency of each character in the strings s and t.
21+
Iterate through the characters of s and update the count in countS.
22+
Similarly, iterate through the characters of t and update the count in countT.
23+
Compare Counts:
24+
25+
Compare the two hash maps. If both maps are identical, then t is an anagram of s.
26+
27+
Examples
28+
29+
Example 1:
30+
Input: s = "anagram", t = "nagaram"
31+
Output: true
32+
33+
Example 2:
34+
Input: s = "rat", t = "car"
35+
Output: false
36+
37+
Constraints
38+
1 <= s.length, t.length <= 5 * 10^4
39+
s and t consist of lowercase English letters.

0 commit comments

Comments
 (0)