VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cpp-program-to-check-whether-two-strings-are-anagram-of-each-other/

⇱ C++ Program To Check Whether Two Strings Are Anagram Of Each Other - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C++ Program To Check Whether Two Strings Are Anagram Of Each Other

Last Updated : 15 Jan, 2026

Two strings are called anagrams if they contain the same characters in the same frequency, but their order is different.

Example:

Input:

Str1 = "abcd"
Str2 ="dabc"

Output:

Strings are Anagram

Different Methods to Check Whether a String Is an Anagram or Not:

In this article, we will learn how to check whether two strings are anagrams of each other in C++ using different efficient approaches.

1. Use Sorting:

Steps:

  1. Sort both strings
  2. Compare the sorted strings

Output
The two strings are not anagram of each other

Explanation:

  • The function checks the length of both strings and returns false if they are not equal, because anagrams must have the same number of characters.
  • Both strings are sorted in alphabetical order so that their characters can be compared easily.
  • A loop compares each character of the sorted strings one by one.
  • If all characters match, the strings are anagrams; otherwise, they are not.

2. Count characters:

  • This method assumes that characters are stored using 8 bits, so there can be 256 possible characters.
  • Two count arrays of size 256 are created, one for each string, and all values are initialized to 0.
  • Each character of both strings is scanned, and the corresponding index in the count array is incremented.
  • Finally, both count arrays are compared; if they are exactly the same, the strings are anagrams.

Output
The two strings are anagram of each other

3. Count characters using one array:

  • This optimized method uses only one count array instead of two.
  • For each character in str1, the corresponding count is incremented, and for each character in str2, the corresponding count is decremented.
  • After processing both strings, if all values in the count array are 0, then the two strings are anagrams of each other.

Output
The two strings are anagram of each other

4. Using unordered_map:

  • Instead of using a fixed-size array of 256 characters, an unordered_map is used to store only the characters that appear in the strings.
  • First, the occurrences of each character in the first string are counted and stored in the unordered_map.
  • Then, while scanning the second string, the count of each character is reduced.
  • Finally, if the count of every character in the unordered_map is 0, the two strings are anagrams; otherwise, they are not.

Output
The two strings are anagram of each other

Related Article:

Comment