Tutorialspoint
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
Functions / MethodsStringsGoogleHCL Technologies
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Here’s a brief explanation of the program:


  • Function Definition: checks if two strings are anagrams.
  • Length Check: If the strings have different lengths, return False.
  • Frequency Counting: Create dictionaries (freq1, freq2) to count character occurrences in both strings.
  • Comparison: Compare the two frequency dictionaries. If they match, return True; otherwise, return False.
  • Function Call & Output: Calling the function with "listen" and "silent" returns True, so the output is:

Submitted Code :