Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Implement solution for 242. Valid Anagram and update README #5

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions Solved-Problems/Valid_Anagram/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import java.util.HashMap;
import java.util.Map;

class Main {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}

Map<Character, Integer> countS = new HashMap<>();
Map<Character, Integer> countT = new HashMap<>();

for (int i = 0; i < s.length(); i++) {
char c1 = s.charAt(i);
countS.put(c1, countS.getOrDefault(c1, 0) + 1);
}

for (int i = 0; i < t.length(); i++) {
char c2 = t.charAt(i);
countT.put(c2, countT.getOrDefault(c2, 0) + 1);
}

for (char c : countS.keySet()) {
if (!countT.containsKey(c) || !countT.get(c).equals(countS.get(c))) {
return false;
}
}

return true;
}
}
39 changes: 39 additions & 0 deletions Solved-Problems/Valid_Anagram/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Valid Anagram
Problem Name: 242. Valid Anagram

Approach: Using Hash Maps

Difficulty: Easy

Link: [Leetcode](https://leetcode.com/problems/valid-anagram/description/)

Explanation:

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.

Solution Explanation

Check Lengths:
First, check if the lengths of the two strings are equal. If not, return false immediately as they cannot be anagrams.
Count Characters:

Use two hash maps to count the frequency of each character in the strings s and t.
Iterate through the characters of s and update the count in countS.
Similarly, iterate through the characters of t and update the count in countT.
Compare Counts:

Compare the two hash maps. If both maps are identical, then t is an anagram of s.

Examples

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

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

Constraints
1 <= s.length, t.length <= 5 * 10^4
s and t consist of lowercase English letters.
Loading