Check if two Strings are Anagrams of each other (original) (raw)

Last Updated : 24 Oct, 2024

Try it on GfG Practice redirect icon

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.

Table of Content

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

C++ `

// C++ Code to check if two Strings are anagram of // each other using Hash map

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