Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Check if two Strings are Anagrams of each other
Next article icon

Check if two Strings are Anagrams of each other

Last Updated : 24 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given two strings s1 and s2 consisting of lowercase characters, the task is to check whether the two given strings are anagrams of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different.

Examples:

Input: s1 = “geeks”  s2 = “kseeg”
Output: true
Explanation: Both the string have same characters with same frequency. So, they are anagrams.

Input: s1 = “allergy”  s2 = “allergic”
Output: false
Explanation: Characters in both the strings are not same. s1 has extra character 'y' and s2 has extra characters 'i' and 'c', so they are not anagrams.

Input: s1 = "g", s2 = "g"
Output: true
Explanation: Characters in both the strings are same, so they are anagrams.

Table of Content

  • [Naive Approach] Using Sorting
  • [Expected Approach 1] Using Hash Map or Dictionary
  • [Expected Approach 2] Using Frequency Array

[Naive Approach] Using Sorting

The idea is that if the strings are anagrams, then their characters will be the same, just rearranged. Therefore, if we sort the characters in both strings, the sorted strings will be identical if the original strings were anagrams. We can simply sort the two given strings and compare them – if they are equal, then the original strings are anagrams of each other.

C++
// C++ Code to check if two Strings are anagrams of  // each other using sorting  #include <algorithm> #include <iostream> using namespace std;  // Function to check if two strings are anagrams bool areAnagrams(string &s1, string &s2) {          // Sort both strings     sort(s1.begin(), s1.end());     sort(s2.begin(), s2.end());      // Compare sorted strings     return s1 == s2; }  int main() {     string s1 = "geeks";     string s2 = "kseeg"; 	cout << (areAnagrams(s1, s2) ? "true" : "false") << endl;      return 0; } 
C
// C Code to check if two Strings are anagrams of  // each other using sorting  #include <stdio.h> #include <string.h>  // Function to compare two characters (used for sorting) int compare(const void *a, const void *b) {     return (*(char *)a - *(char *)b); }  // Function to check if two strings are anagrams int areAnagrams(char *s1, char *s2) {          // Check if lengths are equal     if (strlen(s1) != strlen(s2)) {         return 0;      }      // Sort both strings     qsort(s1, strlen(s1), sizeof(char), compare);     qsort(s2, strlen(s2), sizeof(char), compare);      // Compare sorted strings     return strcmp(s1, s2) == 0; }  int main() {     char s1[] = "geeks";     char s2[] = "kseeg";     printf("%s\n", areAnagrams(s1, s2) ? "true" : "false");      return 0; } 
Java
// Java Code to check if two Strings are anagrams of  // each other using sorting  import java.util.Arrays;  class GfG {      // Function to check if two strings are anagrams     static boolean areAnagrams(String s1, String s2) {                  // Sort both strings         char[] s1Array = s1.toCharArray();         char[] s2Array = s2.toCharArray();         Arrays.sort(s1Array);         Arrays.sort(s2Array);          // Compare sorted strings         return Arrays.equals(s1Array, s2Array);     }      public static void main(String[] args) {         String s1 = "geeks";         String s2 = "kseeg";         System.out.println(areAnagrams(s1, s2));     } } 
Python
# Python Code to check if two Strings are anagram of  # each other using sorting  def areAnagrams(s1, s2):          # Sort both strings     s1 = sorted(s1)     s2 = sorted(s2)      # Compare sorted strings     return s1 == s2  if __name__ == "__main__":     s1 = "geeks"     s2 = "kseeg"     print("true" if areAnagrams(s1, s2) else "false") 
C#
// C# Code to check if two Strings are anagrams of  // each other using sorting  using System;  class GfG {        // Function to check if two strings are anagrams     static bool AreAnagrams(string s1, string s2) {                  // Sort both strings         char[] s1Array = s1.ToCharArray();         char[] s2Array = s2.ToCharArray();         Array.Sort(s1Array);         Array.Sort(s2Array);          // Compare sorted strings         return new string(s1Array) == new string(s2Array);     }      static void Main() {         string s1 = "geeks";         string s2 = "kseeg";         Console.WriteLine(AreAnagrams(s1, s2) ? "true" : "false");     } } 
JavaScript
// JavaScript Code to check if two Strings are anagram of  // each other using sorting  function areAnagrams(s1, s2) {          // Sort both strings     s1 = s1.split('').sort().join('');     s2 = s2.split('').sort().join('');      // Compare sorted strings     return s1 === s2; }  const s1 = "geeks"; const s2 = "kseeg"; console.log(areAnagrams(s1, s2)); 

Output
true 

Time Complexity: O(m*log(m) + n*log(n)), where m and n are length of string s1 and s2 respectively.
Auxiliary Space: O(1) where the strings are mutable but O(n) in languages like Java, Python, C#, etc. where strings are immutable.

[Expected Approach 1] Using Hash Map or Dictionary

The idea is to use a hash map or dictionary count the frequency of each character in both the input strings. If the frequency of every character matches in both strings, then the strings are anagrams.

  • First, count the occurrences of each character in first string.
  • Then, decrement the count for each character in the second string.
  • If the strings are anagrams, all positions in the frequency array should be zero as any non-zero position means that the frequency of that character is not same in both strings.
C++
// C++ Code to check if two Strings are anagram of  // each other using Hash map  #include <algorithm> #include <iostream> #include <vector> #include <unordered_map> using namespace std;  bool areAnagrams(string &s1, string &s2) {          // Create a hashmap to store character frequencies     unordered_map<char, int> charCount;          // Count frequency of each character in string s1     for(char ch: s1)      	charCount[ch] += 1;        // Count frequency of each character in string s2     for(char ch: s2)      	charCount[ch] -= 1;        // Check if all frequencies are zero     for (auto& pair : charCount) {         if (pair.second != 0) {             return false;         }     }          // If all conditions satisfied, they are anagrams     return true; }  int main() {     string s1 = "geeks";     string s2 = "kseeg"; 	cout << (areAnagrams(s1, s2) ? "true" : "false") << endl;      return 0; } 
Java
// Java Code to check if two Strings are anagram of  // each other using Hash map  import java.util.HashMap;  class GfG {          static boolean areAnagrams(String s1, String s2) {                  // Create a hashmap to store character frequencies         HashMap<Character, Integer> charCount = new HashMap<>();                  // Count frequency of each character in string s1         for (char ch : s1.toCharArray())              charCount.put(ch, charCount.getOrDefault(ch, 0) + 1);            // Count frequency of each character in string s2         for (char ch : s2.toCharArray())              charCount.put(ch, charCount.getOrDefault(ch, 0) - 1);            // Check if all frequencies are zero         for (var pair : charCount.entrySet()) {             if (pair.getValue() != 0) {                 return false;             }         }                  // If all conditions satisfied, they are anagrams         return true;     }      public static void main(String[] args) {         String s1 = "geeks";         String s2 = "kseeg";         System.out.println(areAnagrams(s1, s2) ? "true" : "false");     } } 
Python
# Python Code to check if two Strings are anagram of  # each other using Dictionary  def areAnagrams(s1, s2):          # Create a hashmap to store character frequencies     charCount = {}          # Count frequency of each character in string s1     for ch in s1:         charCount[ch] = charCount.get(ch, 0) + 1        # Count frequency of each character in string s2     for ch in s2:         charCount[ch] = charCount.get(ch, 0) - 1        # Check if all frequencies are zero     for value in charCount.values():         if value != 0:             return False          # If all conditions satisfied, they are anagrams     return True  if __name__ == "__main__":     s1 = "geeks"     s2 = "kseeg"     print("true" if areAnagrams(s1, s2) else "false") 
C#
// C# Code to check if two Strings are anagram of  // each other using Dictionary  using System; using System.Collections.Generic;  class GfG {     static bool areAnagrams(string s1, string s2) {                // Create a dictionary to store character frequencies         Dictionary<char, int> charCount = new Dictionary<char, int>();                  // Count frequency of each character in string s1         foreach (char ch in s1)              charCount[ch] = charCount.GetValueOrDefault(ch, 0) + 1;          // Count frequency of each character in string s2         foreach (char ch in s2)              charCount[ch] = charCount.GetValueOrDefault(ch, 0) - 1;          // Check if all frequencies are zero         foreach (var pair in charCount) {             if (pair.Value != 0)                  return false;         }                  // If all conditions satisfied, they are anagrams         return true;     }      static void Main(string[] args) {         string s1 = "geeks";         string s2 = "kseeg";         Console.WriteLine(areAnagrams(s1, s2) ? "true" : "false");     } } 
JavaScript
// JavaScript Code to check if two Strings are anagram of  // each other using Hash map  function areAnagrams(s1, s2) {          // Create a hashmap to store character frequencies     const charCount = {};          // Count frequency of each character in string s1     for (let ch of s1)          charCount[ch] = (charCount[ch] || 0) + 1;      // Count frequency of each character in string s2     for (let ch of s2)          charCount[ch] = (charCount[ch] || 0) - 1;      // Check if all frequencies are zero     for (let key in charCount) {         if (charCount[key] !== 0) {             return false;         }     }          // If all conditions satisfied, they are anagrams     return true; }  const s1 = "geeks"; const s2 = "kseeg"; console.log(areAnagrams(s1, s2) ? "true" : "false"); 

Output
true 

Time Complexity: O(m + n), where m and n are length of string s1 and s2 respectively.
Auxiliary Space: O(26) = O(1). The input strings can only have lowercase letters, so there can be at most 26 distinct characters in the hash map.

[Expected Approach 2] Using Frequency Array

Instead of using a hash map to store the frequency of each character, we can create a frequency array of size 26 by using characters as index in this array. The frequency of ‘a’ is going to be stored at index 0, ‘b’ at 1, and so on. To find the index of a character, we subtract character a’s ASCII value from the ASCII value of the character.

Count character frequency in the first string, then for each character in the second string, decrement its count from the frequency array. If the strings are anagrams, all positions in the frequency array will be zero. Any non-zero position means the frequency of that character is not equal in both the strings.

Working:


C++
// C++ Code to check if two Strings are anagram of  // each other using Frequency Array  #include <algorithm> #include <iostream> #include <vector> using namespace std;  // As the input strings can only have lowercase  // characters, the maximum characters will be 26 const int MAX_CHAR = 26;  bool areAnagrams(string &s1, string &s2) {     vector<int> freq(MAX_CHAR, 0);          // Count frequency of each character in string s1     for(char ch: s1)      	freq[ch - 'a']++;        // Count frequency of each character in string s2     for(char ch: s2)      	freq[ch - 'a']--;        // Check if all frequencies are zero     for (int count : freq) {         if (count != 0)              return false;     }          return true; }  int main() {     string s1 = "geeks";     string s2 = "kseeg"; 	cout << (areAnagrams(s1, s2) ? "true" : "false") << endl;      return 0; } 
C
// C Code to check if two Strings are anagram of  // each other using Frequency Array  #include <stdio.h> #include <string.h> #include <stdbool.h>  // As the input strings can only have lowercase characters #define MAX_CHAR 26   int areAnagrams(char *s1, char *s2) {     int freq[MAX_CHAR] = {0};      // Count frequency of each character in string s1     for (int i = 0; s1[i] != '\0'; i++)          freq[s1[i] - 'a']++;      // Count frequency of each character in string s2     for (int i = 0; s2[i] != '\0'; i++)         freq[s2[i] - 'a']--;      // Check if all frequencies are zero     for (int i = 0; i < MAX_CHAR; i++) {         if (freq[i] != 0) {             return false;         }     }      return true; }  int main() {     char s1[] = "geeks";     char s2[] = "kseeg";     printf("%s\n", areAnagrams(s1, s2) ? "true" : "false");      return 0; } 
Java
// Java Code to check if two Strings are anagram of  // each other using Frequency Array  class GfG {      // As the input strings can only have lowercase      // characters, the maximum characters will be 26     static final int MAX_CHAR = 26;      static boolean areAnagrams(String s1, String s2) {         int[] freq = new int[MAX_CHAR];          // Count frequency of each character in string s1         for (int i = 0; i < s1.length(); i++)             freq[s1.charAt(i) - 'a']++;          // Count frequency of each character in string s2         for (int i = 0; i < s2.length(); i++)             freq[s2.charAt(i) - 'a']--;          // Check if all frequencies are zero         for (int count : freq) {             if (count != 0)                 return false;         }          return true;     }      public static void main(String[] args) {         String s1 = "geeks";         String s2 = "kseeg";         System.out.println(areAnagrams(s1, s2));     } } 
Python
# Python Code to check if two Strings are anagram of  # each other using Frequency Array  # As the input strings can only have lowercase  # characters, the maximum characters will be 26 MAX_CHAR = 26  def areAnagrams(s1, s2):     freq = [0] * MAX_CHAR          # Count frequency of each character in string s1     for ch in s1:         freq[ord(ch) - ord('a')] += 1      # Count frequency of each character in string s2     for ch in s2:         freq[ord(ch) - ord('a')] -= 1      # Check if all frequencies are zero     for count in freq:         if count != 0:             return False                  return True  if __name__ == "__main__":     s1 = "geeks"     s2 = "kseeg"     print("true" if areAnagrams(s1, s2) else "false") 
C#
// C# Code to check if two Strings are anagram of  // each other using Frequency Array  using System;  class GfG {        // As the input strings can only have lowercase      // characters, the maximum characters will be 26     const int MAX_CHAR = 26;      static bool AreAnagrams(string s1, string s2) {         int[] freq = new int[MAX_CHAR];          // Count frequency of each character in string s1         foreach (char ch in s1)             freq[ch - 'a']++;          // Count frequency of each character in string s2         foreach (char ch in s2)             freq[ch - 'a']--;          // Check if all frequencies are zero         foreach (int count in freq) {             if (count != 0)                 return false;         }          return true;     }      static void Main() {         string s1 = "geeks";         string s2 = "kseeg";         Console.WriteLine(AreAnagrams(s1, s2) ? "true" : "false");     } } 
JavaScript
// JavaScript Code to check if two Strings are anagram of  // each other using Frequency Array  // As the input strings can only have lowercase  // characters, the maximum characters will be 26 const MAX_CHAR = 26;  function areAnagrams(s1, s2) {     let freq = new Array(MAX_CHAR).fill(0);          // Count frequency of each character in string s1     for (let ch of s1)          freq[ch.charCodeAt(0) - 'a'.charCodeAt(0)]++;        // Count frequency of each character in string s2     for (let ch of s2)          freq[ch.charCodeAt(0) - 'a'.charCodeAt(0)]--;        // Check if all frequencies are zero     for (let count of freq) {         if (count !== 0)              return false;     }          return true; }  const s1 = "geeks"; const s2 = "kseeg"; console.log(areAnagrams(s1, s2) ? "true" : "false"); 

Output
true 

Time Complexity: O(m + n), where m and n are length of string s1 and s2 respectively.
Auxiliary Space: O(MAX_CHAR) = O(26) = O(1), the input strings can only have lowercase letters, so we only need frequency array of size 26.


Next Article
Check if two Strings are Anagrams of each other

K

kartik
Improve
Article Tags :
  • Strings
  • DSA
  • Amazon
  • Goldman Sachs
  • Nagarro
  • anagram
Practice Tags :
  • Amazon
  • Goldman Sachs
  • Nagarro
  • anagram
  • Strings

Similar Reads

    Check if two strings are k-anagrams or not
    Given two strings of lowercase alphabets and a value k, the task is to find if two strings are K-anagrams of each other or not.Note: Two strings are called k-anagrams if the following two conditions are true. Both have same number of characters.Two strings can become anagram by changing at most k ch
    14 min read
    Check if two Integer are anagrams of each other
    Given two integers A and B, the task is to check whether the given numbers are anagrams of each other or not. Just like strings, a number is said to be an anagram of some other number if it can be made equal to the other number by just shuffling the digits in it.Examples: Input: A = 204, B = 240 Out
    15+ min read
    Check if two strings are permutation of each other
    Write a function to check whether two given strings are Permutation of each other or not. A Permutation of a string is another string that contains same characters, only the order of characters can be different. For example, "abcd" and "dabc" are Permutation of each other. We strongly recommend that
    13 min read
    Javascript Program To Check Whether Two Strings Are Anagram Of Each Other
    Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other.Method 1 (Use Sorting):Sort bot
    6 min read
    Check whether two strings are anagrams of each other using unordered_map in C++
    Write a function to check whether two given strings are an Anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an Anagram of each other. Approach: Unordered Map can
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences