
Problem
Solution
Submissions
Check if Two Strings are Anagrams
Certification: Basic Level
Accuracy: 80%
Submissions: 5
Points: 5
Write a C# program to determine if two strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Algorithm
- Step 1: Check if the lengths of both strings are equal. If not, they cannot be anagrams.
- Step 2: Count the frequency of each character in both strings.
- Step 3: Compare the character frequencies. If they match for all characters, the strings are anagrams.
- Step 4: Return true if the strings are anagrams, false otherwise.
Example 1
- Input: s = "listen", t = "silent"
- Output: true
- Explanation:
- Both strings have the same length (6 characters).
- Both strings contain the same characters with the same frequencies:
- 'l' appears once in both strings
- 'i' appears once in both strings
- 's' appears once in both strings
- 't' appears once in both strings
- 'e' appears once in both strings
- 'n' appears once in both strings
Example 2
- Input: s = "rat", t = "car"
- Output: false
- Explanation:
- Both strings have the same length (3 characters).
- The character frequencies do not match:
- 'r' appears once in "rat" and once in "car"
- 'a' appears once in "rat" and once in "car"
- 't' appears once in "rat" but not in "car"
- 'c' appears once in "car" but not in "rat"
Constraints
- 1 ≤ s.length, t.length ≤ 5 * 10^4
- s and t consist of lowercase English letters
- Time Complexity: O(n)
- Space Complexity: O(1) since we're only dealing with lowercase English letters
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- You can use an array of size 26 to count the frequency of each character in both strings
- Alternatively, you can use a dictionary or hash table to count character frequencies
- Consider sorting both strings and then comparing them character by character
- Remember to handle edge cases like different lengths or empty strings