Check if two strings are anagrams or not in C, C++, Java and Python | faceprep

Check if two strings are anagrams or not in C, C++, Java and Python | faceprep

Program to check if two strings are anagrams or not is discussed here. Two strings are given as input and those strings have to be checked if they are anagrams or not. Anagram means that both strings contain the same character set, only their order is different. Therefore, in both strings, the frequency of each letter must be the same. For example, strings “act” and “cat” are anagrams.



Check if Two Strings are anagrams or not



The solution to this problem can be given in two different ways.

Method 1: Count the frequency of alphabets in both the strings and store them in respective arrays. If the two arrays are equal, return true. Else, return false.

Method 2: Sort both the strings and compare if both the sorted strings are equal. If they are equal, return true. Else, return false



Algorithm to check if two strings are anagrams or not

  • Input the two strings.
  • Create an array for both the strings.
  • Traverse both the strings and store the count of the alphabets of both the strings in respective arrays.
  • Check if both the arrays are equal.
  • If both the arrays are equal, return true. Else, return false.




Program to check if two strings are anagrams or not?

@@coding::2@@




Algorithm to check if two strings are anagrams or not using sorting technique

  • Input the strings.
  • Sort both the strings.
  • If both the strings are equal, return true. Else, return false.


@@coding::1@@


Recommended Programs