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

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.

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++ `

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

#include #include #include #include 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 #include 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"); }

`