Check if two Strings are Anagrams of each other
Last Updated :
24 Oct, 2024
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.
[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));
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");
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");
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.
Similar Reads
Check if two Strings are Anagrams of each other
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 = “geek
13 min read
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.Two strings are called k-anagrams if following two conditions are true. Both have same number of characters.Two strings can become anagram by changing at most k characters i
15+ 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
14 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. We strongly recommend that you
7 min read
Check if Strings Are Rotations of Each Other
Given two string s1 and s2 of same length, the task is to check whether s2 is a rotation of s1. Examples: Input: s1 = "abcd", s2 = "cdab"Output: trueExplanation: After 2 right rotations, s1 will become equal to s2. Input: s1 = "aab", s2 = "aba"Output: trueExplanation: After 1 left rotation, s1 will
15+ 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
Check if all levels of two trees are anagrams or not
Given two binary trees, we have to check if each of their levels is an anagram of the other or not. Example: Tree 1:Level 0 : 1Level 1 : 3, 2Level 2 : 5, 4Tree 2:Level 0 : 1Level 1 : 2, 3Level 2 : 4, 5As we can clearly see all the levels of above two binary trees are anagrams of each other, hence
15+ min read
Check if two strings are same or not
Given two strings, the task is to check if these two strings are identical(same) or not. Examples: Input: s1 = "abc", s2 = "abc" Output: Yes Input: s1 = "", s2 = "" Output: Yes Input: s1 = "GeeksforGeeks", s2 = "Geeks" Output: No Using (==) in C++/Python/C#, equals in Java and === in JavaScript[GFGT
3 min read
Check if a String is Interleaving of Other Two
Given three strings s1, s2 and s3. Write a function that checks whether s3 is an interleaving of s1 and s2. s3 is said to be interleaving s1 and s2, if it contains all and only characters of s1 and s2 and order of all characters in individual strings is preserved. Input: s1 = "AB", s2 = "C", s3 = "A
15+ min read
Check if binary representations of two numbers are anagram
Given two numbers you are required to check whether they are anagrams of each other or not in binary representation.Examples: Input : a = 8, b = 4 Output : Yes Binary representations of both numbers have same 0s and 1s. Input : a = 4, b = 5 Output : No Simple Approach: Find the Binary Representation
9 min read
Check whether Strings are k distance apart or not
Given two strings, the task is to find if they are only less than or equal to k edit distance apart. It means that strings are only k edit distance apart when there are only k mismatches. Print Yes if there are less than or equal to k mismatches, Else No. Also, print yes if both strings are already
11 min read
Check if strings are rotations of each other or not | Set 2
Given two strings s1 and s2, check whether s2 is a rotation of s1. Examples: Input : ABACD, CDABA Output : True Input : GEEKS, EKSGE Output : True We have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm's lps (long
6 min read
Check if two strings can be made equal by swapping one character among each other
Given two strings A and B of length N, the task is to check whether the two strings can be made equal by swapping any character of A with any other character of B only once.Examples: Input: A = "SEEKSFORGEEKS", B = "GEEKSFORGEEKG" Output: Yes "SEEKSFORGEEKS" and "GEEKSFORGEEKG" After removing the el
10 min read
Check if characters of one string can be swapped to form other
Two strings are given, we need to find whether we can form second string by swapping the character of the first string. Examples: Input : str1 = "geeksforgeeks" str2 = "geegeeksksfor" Output : YES Input : str1 = "geeksfor" str2 = "geeekfor" Output : NO First of all, we will find the length of string
6 min read
Check if all given strings are isograms or not
Given an array arr containing N strings, the task is to check if all strings are isogram or not. If they are, print Yes, otherwise No. An Isogram is a word in which no letter occurs more than once. Examples: Input: arr[] = {"abcd", "derg", "erty"}Output: Yes Input: arr[] = {"agka", "lkmn"}Output: No
4 min read
Check whether two Linked Lists are anagrams or not
Given two strings in the form of linked lists, the task is to check if one string is the anagram of the other. Print Yes if they are, otherwise print No. Examples: Input: Linked List 1 = T->R->I->A->N->G->L->E->NULLLinked List 2 = I->N->T->E->G->R->A->L-
15 min read
Check if two given strings are isomorphic to each other | Set 2 (Using STL)
Given two strings str1 and str2, the task is to check if the two strings are isomorphic to each other. Two strings str1 and str2 are called isomorphic if there is a one-to-one mapping possible for every character of str1 to every character of str2 and all occurrences of every character in ‘str1’ map
6 min read
Check if given words are present in a string
Given a big string and an array of small strings, all of which are smaller in length than the big string. The task is to create an array of booleans, where each boolean represents whether the small string at that index in the array of small strings is contained in the big string. Note : that you can
15+ min read