Check if two Strings are Anagrams of each other
Last Updated :
25 Jul, 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 + m) 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 + m) 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
Basics & Prerequisites
Data Structures
Array Data StructureIn 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
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA 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
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem