
Problem
Solution
Submissions
Check if Two Strings are Anagrams
Certification: Basic Level
Accuracy: 62.26%
Submissions: 53
Points: 15
Write a Python program that determines if two strings are anagrams of each other. Two strings are anagrams if they contain the same characters with the same frequencies, regardless of order.
Example 1
- Input: string1 = "listen", string2 = "silent"
- Output: True
- Explanation:
- Step 1: Count the frequency of each character in both strings.
- Step 2: "listen" has {'l':1, 'i':1, 's':1, 't':1, 'e':1, 'n':1}.
- Step 3: "silent" has {'s':1, 'i':1, 'l':1, 'e':1, 'n':1, 't':1}.
- Step 4: Since both strings have the same characters with the same frequencies, they are anagrams.
Example 2
- Input: string1 = "hello", string2 = "world"
- Output: False
- Explanation:
- Step 1: Count the frequency of each character in both strings.
- Step 2: "hello" has {'h':1, 'e':1, 'l':2, 'o':1}.
- Step 3: "world" has {'w':1, 'o':1, 'r':1, 'l':1, 'd':1}.
- Step 4: The strings have different characters, so they are not anagrams.
Constraints
- 1 ≤ len(string) ≤ 10^6
- Strings contain only lowercase letters
- Time Complexity: O(n) where n is the length of the string
- Space Complexity: O(1) since we only need to store 26 characters at most
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
- Sort both strings and compare: sorted(s1) == sorted(s2)
- Use Counter from collections: Counter(s1) == Counter(s2)
- Create frequency maps and compare: create dictionaries for character counts in both strings and compare
- If the strings have different lengths, they cannot be anagrams