Tutorialspoint
Problem
Solution
Submissions

Check if Two Strings are Anagrams

Certification: Basic Level Accuracy: 77.78% Submissions: 9 Points: 10

Write a Python program that checks if two given 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.

Example 1
  • Input: string1 = "listen", string2 = "silent"
  • Output: true
  • Explanation:
    • Step 1: Count the frequency of each character in the first string.
    • Step 2: Count the frequency of each character in the second string.
    • Step 3: Compare the character frequencies from both strings.
    • Step 4: Return true since both strings have identical character frequencies.
Example 2
  • Input: string1 = "hello", string2 = "world"
  • Output: false
  • Explanation:
    • Step 1: Count the frequency of each character in the first string.
    • Step 2: Count the frequency of each character in the second string.
    • Step 3: Compare the character frequencies from both strings.
    • Step 4: Return false since the character frequencies are different.
Constraints
  • 1 ≤ len(string1), len(string2) ≤ 10^6
  • Strings contain only lowercase English letters
  • Time Complexity: O(n), where n is the length of the strings
  • Space Complexity: O(1)
ArraysStringsCapgeminiLTIMindtree
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

  • Check if the lengths of the two strings are the same.
  • Use a frequency array or hash map to count the occurrences of each character in both strings.
  • Compare the frequency arrays or hash maps to determine if the strings are anagrams.

Steps to solve by this approach:

 Step 1: Define a function areAnagrams that takes two constant string references.
 Step 2: Check if the lengths of both strings are equal; if not, return false.
 Step 3: Create an array to count occurrences of each character (assuming lowercase letters only).
 Step 4: Increment counters for characters in the first string.
 Step 5: Decrement counters for characters in the second string.
 Step 6: Check if all counters are zero after processing both strings.
 Step 7: Return true if all counters are zero, false otherwise.

Submitted Code :