Check if two Strings are Anagrams of each other
Last Updated :
30 Jun, 2025
Given two non-empty strings s1 and s2 of lowercase letters, determine if they are anagrams — i.e., if they contain the same characters with the same frequencies.
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 = "allergyy"
Output: false
Explanation: Although the characters are mostly the same, s2 contains an extra 'y' character. Since the frequency of characters differs, the strings are not anagrams.
Input: s1 = "listen", s2 = "lists"
Output: false
Explanation: The characters in the two strings are not the same — some are missing or extra. So, they are not 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++
#include <algorithm>
#include <iostream>
using namespace std;
bool areAnagrams(string &s1, string &s2) {
if (s1.length() != s2.length())
return false;
// 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";
if(areAnagrams(s1, s2)){
cout << "true" << endl;
}
else{
cout << "false" << endl;
}
return 0;
}
C
#include <stdio.h>
#include <string.h>
// For using bool type
#include <stdbool.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
bool areAnagrams(char *s1, char *s2) {
if (strlen(s1) != strlen(s2)) return false;
// 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";
if (areAnagrams(s1, s2)) {
printf("true\n");
} else {
printf("false\n");
}
return 0;
}
Java
import java.util.Arrays;
class GfG {
static boolean areAnagrams(String s1, String s2) {
if (s1.length() != s2.length()) return false;
// 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";
if(areAnagrams(s1, s2) == true){
System.out.println("true");
}
else{
System.out.println("false");
}
}
}
Python
def areAnagrams(s1, s2):
if len(s1) != len(s2):
return False
# Sort both strings
s1 = sorted(s1)
s2 = sorted(s2)
# Compare sorted strings
return s1 == s2
if __name__ == "__main__":
s1 = "geeks"
s2 = "kseeg"
if(areAnagrams(s1,s2)):
print("true")
else:
print("false")
C#
using System;
class GfG {
static bool areAnagrams(string s1, string s2) {
if (s1.Length != s2.Length) return false;
// 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";
if(areAnagrams(s1, s2)){
Console.WriteLine("true");
}
else{
Console.WriteLine("false");
}
}
}
JavaScript
function areAnagrams(s1, s2) {
if (s1.length !== s2.length) return false;
// Sort both strings
s1 = s1.split('').sort().join('');
s2 = s2.split('').sort().join('');
// Compare sorted strings
return s1 === s2;
}
// Driver Code
const s1 = "geeks";
const s2 = "kseeg";
if(areAnagrams(s1, s2)){
console.log("true");
}
else{
console.log("false");
}
Time Complexity: O(m*log(m) + n*log(n))
Auxiliary Space: In languages like C or C++, where strings can be mutable and sorted in place, the auxiliary space used is O(1). However, in languages such as Java, Python, C# and JavaScript where strings are immutable, sorting operations typically create new copies of the strings, leading to an space used is O(m + n).
[Expected Approach 1] Using Hash Map or Dictionary - O(n) Time and O(1) Space
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.
Step by Step Approach:
- First, count the occurrences of each character in the first string using a HashMap.
- Then, iterate through the second string and decrement the corresponding count for each character in the same HashMap.
- After processing both strings, check the HashMap: if all character counts are zero, the strings are anagrams
- Any non-zero count indicates a mismatch in character frequency, meaning the strings are not anagrams.
C++
#include <algorithm>
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
bool areAnagrams(string &s1, string &s2) {
if(s1.size() != s2.size()){
return false;
}
// 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;
}
}
return true;
}
int main() {
string s1 = "geeks";
string s2 = "kseeg";
if(areAnagrams(s1, s2)){
cout << "true";
}
else{
cout << "false";
}
return 0;
}
Java
import java.util.HashMap;
class GfG {
static boolean areAnagrams(String s1, String s2) {
if(s1.length() != s2.length()){
return false;
}
// 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;
}
}
return true;
}
public static void main(String[] args) {
String s1 = "geeks";
String s2 = "kseeg";
System.out.println(areAnagrams(s1, s2) ? "true" : "false");
}
}
Python
def areAnagrams(s1, s2):
if len(s1) != len(s2):
return False
# 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
return True
if __name__ == "__main__":
s1 = "geeks"
s2 = "kseeg"
if areAnagrams(s1, s2):
print("true")
else:
print("false")
C#
using System;
using System.Collections.Generic;
class GfG {
static bool areAnagrams(string s1, string s2) {
if (s1.Length != s2.Length) return false;
// 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;
}
return true;
}
static void Main(string[] args) {
string s1 = "geeks";
string s2 = "kseeg";
if(areAnagrams(s1, s2)){
Console.WriteLine("true");
}
else{
Console.WriteLine("false");
}
}
}
JavaScript
function areAnagrams(s1, s2) {
if (s1.length !== s2.length) return false;
// 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;
}
}
return true;
}
// Driver Code
const s1 = "geeks";
const s2 = "kseeg";
if(areAnagrams(s1, s2)){
console.log("true");
}
else{
console.log("false");
}
[Expected Approach 2] Using Frequency Array - O(n) Time and O(1) Space
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++
#include <iostream>
#include <vector>
using namespace std;
bool areAnagrams(string &s1, string &s2) {
if (s1.length() != s2.length()) return false;
// for lowercase a-z
vector<int> freq(26, 0);
// Count frequency of each character in s1
for(char ch : s1)
freq[ch - 'a']++;
// Subtract frequency using characters from s2
for(char ch : s2)
freq[ch - 'a']--;
// If any count is not zero, not an anagram
for(int count : freq) {
if (count != 0)
return false;
}
return true;
}
int main() {
string s1 = "geeks";
string s2 = "kseeg";
if (areAnagrams(s1, s2))
cout << "true" << endl;
else
cout << "false" << endl;
return 0;
}
C
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool areAnagrams(char *s1, char *s2) {
if (strlen(s1) != strlen(s2)) return false;
// for lowercase a-z
int freq[26] = {0};
// Count frequency of each character in s1
for (int i = 0; s1[i] != '\0'; i++)
freq[s1[i] - 'a']++;
// Subtract frequency using characters from s2
for (int i = 0; s2[i] != '\0'; i++)
freq[s2[i] - 'a']--;
// Check if all frequencies are zero
for (int i = 0; i < 26; i++) {
if (freq[i] != 0)
return false;
}
return true;
}
int main() {
char s1[] = "geeks";
char s2[] = "kseeg";
if (areAnagrams(s1, s2))
printf("true\n");
else
printf("false\n");
return 0;
}
Java
class GfG {
static boolean areAnagrams(String s1, String s2) {
if (s1.length() != s2.length()) return false;
// for lowercase a-z
int[] freq = new int[26];
// Count frequency of each character in s1
for (int i = 0; i < s1.length(); i++)
freq[s1.charAt(i) - 'a']++;
// Subtract frequency using characters from 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";
if (areAnagrams(s1, s2))
System.out.println("true");
else
System.out.println("false");
}
}
Python
def areAnagrams(s1, s2):
if len(s1) != len(s2):
return False
# for lowercase a-z
freq = [0] * 26
# Count frequency of each character in s1
for ch in s1:
freq[ord(ch) - ord('a')] += 1
# Subtract frequency using characters from 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"
if areAnagrams(s1, s2):
print("true")
else:
print("false")
C#
using System;
class GfG {
static bool areAnagrams(string s1, string s2) {
if (s1.Length != s2.Length) return false;
// for lowercase a-z
int[] freq = new int[26];
// Count frequency of each character in s1
foreach (char ch in s1)
freq[ch - 'a']++;
// Subtract frequency using characters from 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";
if (areAnagrams(s1, s2))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
JavaScript
function areAnagrams(s1, s2) {
if (s1.length !== s2.length) return false;
// for lowercase a-z
let freq = new Array(26).fill(0);
// Count frequency of each character in s1
for (let ch of s1)
freq[ch.charCodeAt(0) - 'a'.charCodeAt(0)]++;
// Subtract frequency using characters from 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;
}
// Driver Code
const s1 = "geeks";
const s2 = "kseeg";
if (areAnagrams(s1, s2)) {
console.log("true");
} else {
console.log("false");
}
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read