 Company-Specific Courses
Free Resources Edit Edit

# Check if Two Strings are anagrams or not in C, C++, Java and Python | Face Prep

Published on 10 Mar 2020

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. 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?

C
C++
Java

Output
Enter two Strings:
cat
act
Output : The strings are anagrams

Time complexity: O(n)

## 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.

C++
Java
Python 3

Output
String 1: cat
String 2 : act
The two strings are anagram of each other

Recommended Programs

﻿  