Check if two Integer are anagrams of each other
Last Updated :
07 Jan, 2024
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
Output: Yes
Input: A = 23, B = 959
Output: No
Approach: Create two arrays freqA[] and freqB[] where freqA[i] and freqB[i] will store the frequency of digit i in a and b respectively. Now traverse the frequency arrays and for any digit i if freqA[i] != freqB[i] then the numbers are not anagrams of each other else they are.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
const int TEN = 10;
// Function to update the frequency array
// such that freq[i] stores the
// frequency of digit i in n
void updateFreq(int n, int freq[])
{
// While there are digits
// left to process
while (n) {
int digit = n % TEN;
// Update the frequency of
// the current digit
freq[digit]++;
// Remove the last digit
n /= TEN;
}
}
// Function that returns true if a and b
// are anagarams of each other
bool areAnagrams(int a, int b)
{
// To store the frequencies of
// the digits in a and b
int freqA[TEN] = { 0 };
int freqB[TEN] = { 0 };
// Update the frequency of
// the digits in a
updateFreq(a, freqA);
// Update the frequency of
// the digits in b
updateFreq(b, freqB);
// Match the frequencies of
// the common digits
for (int i = 0; i < TEN; i++) {
// If frequency differs for any digit
// then the numbers are not
// anagrams of each other
if (freqA[i] != freqB[i])
return false;
}
return true;
}
// Driver code
int main()
{
int a = 240, b = 204;
if (areAnagrams(a, b))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java implementation of the approach
import java.io.*;
class GFG
{
static final int TEN = 10;
// Function to update the frequency array
// such that freq[i] stores the
// frequency of digit i in n
static void updateFreq(int n, int [] freq)
{
// While there are digits
// left to process
while (n > 0)
{
int digit = n % TEN;
// Update the frequency of
// the current digit
freq[digit]++;
// Remove the last digit
n /= TEN;
}
}
// Function that returns true if a and b
// are anagarams of each other
static boolean areAnagrams(int a, int b)
{
// To store the frequencies of
// the digits in a and b
int [] freqA = new int[TEN];
int [] freqB = new int[TEN];
// Update the frequency of
// the digits in a
updateFreq(a, freqA);
// Update the frequency of
// the digits in b
updateFreq(b, freqB);
// Match the frequencies of
// the common digits
for (int i = 0; i < TEN; i++)
{
// If frequency differs for any digit
// then the numbers are not
// anagrams of each other
if (freqA[i] != freqB[i])
return false;
}
return true;
}
// Driver code
public static void main (String[] args)
{
int a = 204, b = 240;
if (areAnagrams(a, b))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by ihirtik
Python3
# Python3 implementation of the approach
TEN = 10
# Function to update the frequency array
# such that freq[i] stores the
# frequency of digit i in n
def updateFreq(n, freq) :
# While there are digits
# left to process
while (n) :
digit = n % TEN
# Update the frequency of
# the current digit
freq[digit] += 1
# Remove the last digit
n //= TEN
# Function that returns true if a and b
# are anagarams of each other
def areAnagrams(a, b):
# To store the frequencies of
# the digits in a and b
freqA = [ 0 ] * TEN
freqB = [ 0 ] * TEN
# Update the frequency of
# the digits in a
updateFreq(a, freqA)
# Update the frequency of
# the digits in b
updateFreq(b, freqB)
# Match the frequencies of
# the common digits
for i in range(TEN):
# If frequency differs for any digit
# then the numbers are not
# anagrams of each other
if (freqA[i] != freqB[i]):
return False
return True
# Driver code
a = 240
b = 204
if (areAnagrams(a, b)):
print("Yes")
else:
print("No")
# This code is contributed by
# divyamohan123
C#
// C# implementation of the approach
using System;
class GFG
{
static int TEN = 10;
// Function to update the frequency array
// such that freq[i] stores the
// frequency of digit i in n
static void updateFreq(int n, int [] freq)
{
// While there are digits
// left to process
while (n > 0)
{
int digit = n % TEN;
// Update the frequency of
// the current digit
freq[digit]++;
// Remove the last digit
n /= TEN;
}
}
// Function that returns true if a and b
// are anagarams of each other
static bool areAnagrams(int a, int b)
{
// To store the frequencies of
// the digits in a and b
int [] freqA = new int[TEN];
int [] freqB = new int[TEN];;
// Update the frequency of
// the digits in a
updateFreq(a, freqA);
// Update the frequency of
// the digits in b
updateFreq(b, freqB);
// Match the frequencies of
// the common digits
for (int i = 0; i < TEN; i++)
{
// If frequency differs for any digit
// then the numbers are not
// anagrams of each other
if (freqA[i] != freqB[i])
return false;
}
return true;
}
// Driver code
public static void Main ()
{
int a = 204, b = 240;
if (areAnagrams(a, b))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by ihirtik
JavaScript
<script>
// Javascript implementation of the approach
const TEN = 10;
// Function to update the frequency array
// such that freq[i] stores the
// frequency of digit i in n
function updateFreq(n, freq)
{
// While there are digits
// left to process
while (n) {
let digit = n % TEN;
// Update the frequency of
// the current digit
freq[digit]++;
// Remove the last digit
n = parseInt(n / TEN);
}
}
// Function that returns true if a and b
// are anagarams of each other
function areAnagrams(a, b)
{
// To store the frequencies of
// the digits in a and b
let freqA = new Array(TEN).fill(0);
let freqB = new Array(TEN).fill(0);
// Update the frequency of
// the digits in a
updateFreq(a, freqA);
// Update the frequency of
// the digits in b
updateFreq(b, freqB);
// Match the frequencies of
// the common digits
for (let i = 0; i < TEN; i++) {
// If frequency differs for any digit
// then the numbers are not
// anagrams of each other
if (freqA[i] != freqB[i])
return false;
}
return true;
}
// Driver code
let a = 240, b = 204;
if (areAnagrams(a, b))
document.write("Yes");
else
document.write("Yes");
</script>
Time Complexity: O(log10a+log10b)
Auxiliary Space: O(1) as constant space is required.
Method #2 :Using sorting():
- Convert two integers to string.
- Sort the strings and check if they are equal.
- Print Yes if they are equal.
- Else no.
Below is the implementation:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function that returns true if a and b
// are anagarams of each other
bool areAnagrams(int a, int b)
{
// Converting numbers to strings
string c = to_string(a);
string d = to_string(b);
// Checking if the sorting values
// of two strings are equal
sort(c.begin(), c.end());
sort(d.begin(), d.end());
if (c == d)
return true;
else
return false;
}
// Driver code
int main()
{
int a = 240;
int b = 204;
if (areAnagrams(a, b))
cout << "Yes";
else
cout << "No";
}
// This code is contributed by ukasp.
Java
// Java implementation of the approach
import java.io.*;
class GFG {
// Function that returns true if a and b
// are anagarams of each other
static boolean areAnagrams(int a, int b)
{
// Converting numbers to strings
char[] c = (String.valueOf(a)).toCharArray();
char[] d = (String.valueOf(b)).toCharArray();
// Checking if the sorting values
// of two strings are equal
Arrays.sort(c);
Arrays.sort(d);
return (Arrays.equals(c, d));
}
// Driver code
public static void main(String[] args)
{
int a = 240;
int b = 204;
System.out.println((areAnagrams(a, b)) ? "Yes"
: "No");
}
}
// This code is contributed by phasing17.
Python3
# Python3 implementation of the approach
# Function that returns true if a and b
# are anagarams of each other
def areAnagrams(a, b):
# Converting numbers to strings
a = str(a)
b = str(b)
# Checking if the sorting values
# of two strings are equal
if(sorted(a) == sorted(b)):
return True
else:
return False
# Driver code
a = 240
b = 204
if (areAnagrams(a, b)):
print("Yes")
else:
print("No")
# This code is contributed by vikkycirus
C#
// C# implementation of the approach
using System;
using System.Linq;
using System.Collections.Generic;
class GFG
{
// Function that returns true if a and b
// are anagarams of each other
static bool areAnagrams(int a, int b)
{
// Converting numbers to strings
char[] c = (Convert.ToString(a)).ToCharArray();
char[] d = (Convert.ToString(b)).ToCharArray();
// Checking if the sorting values
// of two strings are equal
Array.Sort(c);
Array.Sort(d);
return (c.SequenceEqual(d));
}
// Driver code
public static void Main(string[] args)
{
int a = 240;
int b = 204;
Console.WriteLine((areAnagrams(a, b)) ? "Yes"
: "No");
}
}
// This code is contributed by phasing17.
JavaScript
<script>
// JavaScript implementation of the approach
// Function that returns true if a and b
// are anagarams of each other
function areAnagrams(a, b){
// Converting numbers to strings
a = a.toString().split("").sort().join("")
b = b.toString().split("").sort().join("")
// Checking if the sorting values
// of two strings are equal
if(a == b){
return true
}
else
return false
}
// Driver code
let a = 240
let b = 204
if (areAnagrams(a, b))
document.write("Yes")
else
document.write("No")
// This code is contributed by shinjanpatra
</script>
Time Complexity: O(d1*log(d1)+d2*log(d2)) where d1=log10a and d2=log10b
Auxiliary Space: O(d1+d2)
Approach#3: Using character count arrays
Convert both integers into strings. Create character count arrays for both strings. Compare the character count arrays to check if they are equal
Algorithm
1. Convert both integers A and B into strings a and b
2. If the lengths of a and b are different, return False
3. Create two arrays count_a and count_b of size 10 (one for each digit)
4. Initialize all elements of count_a and count_b to 0
5. Traverse a and increment the count of the digit at each index in count_a
6. Traverse b and increment the count of the digit at each index in count_b
7. If count_a is equal to count_b, return True, else return False
C++
#include <bits/stdc++.h>
using namespace std;
// Function to check if two integers are anagrams of each other
string is_anagram(int A, int B)
{
// Convert integers to strings
string a = to_string(A);
string b = to_string(B);
// Check if the length of both strings is equal
if (a.length() != b.length()) {
return "No";
}
// Create two vectors of size 10 and initialize all elements to 0
vector<int> count_a(10, 0);
vector<int> count_b(10, 0);
// Iterate over both strings and increment the count of each digit in the respective vectors
for (int i = 0; i < a.length(); i++) {
count_a[a[i] - '0']++;
count_b[b[i] - '0']++;
}
// Check if both vectors are equal
if (count_a == count_b) {
return "Yes";
} else {
return "No";
}
}
// Driver function to test the is_anagram function
int main()
{
int A = 240;
int B = 204;
cout << is_anagram(A, B) << endl;
return 0;
}
Java
import java.util.Arrays;
class GFG {
// Function to check if two integers are anagrams of each other
public static String is_anagram(int A, int B) {
// Convert integers to strings
String a = Integer.toString(A);
String b = Integer.toString(B);
// Check if the length of both strings is equal
if (a.length() != b.length()) {
return "No";
}
// Create two arrays of size 10 and initialize all elements to 0
int[] count_a = new int[10];
int[] count_b = new int[10];
// Iterate over both strings and increment the count of each digit in the respective arrays
for (int i = 0; i < a.length(); i++) {
count_a[a.charAt(i) - '0']++;
count_b[b.charAt(i) - '0']++;
}
// Check if both arrays are equal
if (Arrays.equals(count_a, count_b)) {
return "Yes";
} else {
return "No";
}
}
// Driver function to test the is_anagram function
public static void main(String[] args) {
int A = 240;
int B = 204;
System.out.println(is_anagram(A, B));
}
}
Python3
def is_anagram(A, B):
a = str(A)
b = str(B)
if len(a) != len(b):
return False
count_a = [0] * 10
count_b = [0] * 10
for i in range(len(a)):
count_a[int(a[i])] += 1
count_b[int(b[i])] += 1
if count_a == count_b:
return 'Yes'
else:
return 'No'
A = 240
B = 204
print(is_anagram(A, B))
C#
using System;
using System.Linq;
class GFG
{
// Function to check if two integers are anagrams of each other
public static string IsAnagram(int A, int B)
{
// Convert integers to strings
string a = A.ToString();
string b = B.ToString();
// Check if the length of both strings is equal
if (a.Length != b.Length)
{
return "No";
}
// Create two arrays of size 10 and initialize all elements to 0
int[] count_a = new int[10];
int[] count_b = new int[10];
// Iterate over both strings and increment the count of each digit in the respective arrays
for (int i = 0; i < a.Length; i++)
{
count_a[a[i] - '0']++;
count_b[b[i] - '0']++;
}
// Check if both arrays are equal
if (count_a.Intersect(count_b).Any())
{
return "Yes";
}
else
{
return "No";
}
}
// Driver function to test the IsAnagram function
public static void Main(string[] args)
{
int A = 240;
int B = 204;
Console.WriteLine(IsAnagram(A, B));
}
}
JavaScript
// Function to check if two integers are anagrams of each other
function is_anagram(A, B) {
// Convert integers to strings
let a = A.toString();
let b = B.toString();
// Check if the length of both strings is equal
if (a.length !== b.length) {
return "No";
}
// Create two arrays of size 10 and initialize all elements to 0
let count_a = new Array(10).fill(0);
let count_b = new Array(10).fill(0);
// Iterate over both strings and increment the count of each digit in the respective arrays
for (let i = 0; i < a.length; i++) {
count_a[parseInt(a.charAt(i))] += 1;
count_b[parseInt(b.charAt(i))] += 1;
}
// Check if both arrays are equal
if (count_a.toString() === count_b.toString()) {
return "Yes";
} else {
return "No";
}
}
// Driver code to test the is_anagram function
let A = 240;
let B = 204;
console.log(is_anagram(A, B));
Time Complexity: O(n),
Space Complexity: O(1)
METHOD 4:Using set function in Python.
APPROACH:
This program checks if two integers are anagrams of each other. Two numbers are anagrams of each other if they contain the same digits in different order.
ALGORITHM:
1. Define a function is_anagram that takes two integers as input.
2. Convert the integers to strings and compare the set of their characters.
3. If the sets are equal, the two numbers are anagrams, otherwise they are not.
4. In the main code, call the is_anagram function with the two numbers as input.
5. If the function returns True, print "Yes", otherwise print "No".
C++
#include <iostream>
#include <string>
#include <unordered_set>
#include <algorithm>
bool isAnagram(int a, int b) {
// Convert integers to strings
std::string strA = std::to_string(a);
std::string strB = std::to_string(b);
// Sort the characters in the strings
std::sort(strA.begin(), strA.end());
std::sort(strB.begin(), strB.end());
// Check if the sorted strings are equal
return strA == strB;
}
int main() {
// Sample input
int a = 204;
int b = 240;
// Check if a and b are anagrams of each other
if (isAnagram(a, b))
std::cout << "Yes" << std::endl;
else
std::cout << "No" << std::endl;
return 0;
}
Java
import java.util.*;
import java.util.stream.*;
class GFG {
static boolean IsAnagram(int a, int b) {
return new HashSet<>(String.valueOf(a).chars().mapToObj(c -> (char) c).collect(Collectors.toSet()))
.equals(new HashSet<>(String.valueOf(b).chars().mapToObj(c -> (char) c).collect(Collectors.toSet())));
}
public static void main(String[] args) {
// Sample input
int a = 204;
int b = 240;
// Check if a and b are anagrams of each other
if (IsAnagram(a, b))
System.out.println("Yes");
else
System.out.println("No");
}
}
Python3
def is_anagram(a, b):
return set(str(a)) == set(str(b))
# Sample Input
a = 204
b = 240
# Check if a and b are anagrams of each other
if is_anagram(a, b):
print("Yes")
else:
print("No")
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG
{
static bool IsAnagram(int a, int b)
{
return new HashSet<char>(a.ToString()).SetEquals(b.ToString());
}
static void Main(string[] args)
{
// Sample input
int a = 204;
int b = 240;
// Check if a and b are anagrams of each other
if (IsAnagram(a, b))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
JavaScript
function isAnagram(a, b) {
const aSet = new Set(String(a).split(""));
const bSet = new Set(String(b).split(""));
if (aSet.size !== bSet.size) {
return false;
}
for (const char of aSet) {
if (!bSet.has(char)) {
return false;
}
}
return true;
}
// Sample input
const a = 204;
const b = 240;
// Check if a and b are anagrams of each other
if (isAnagram(a, b)) {
console.log("Yes");
} else {
console.log("No");
}
Time Complexity:
The time complexity of the program is O(n), where n is the length of the input numbers in digits. Converting integers to strings and comparing sets takes linear time.
Space Complexity:
The space complexity of the program is O(n), where n is the length of the input numbers in digits. This is because the program needs to store the strings representing the input numbers in memory.
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 = âgeeks
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.Note: Two strings are called k-anagrams if the following two conditions are true. Both have same number of characters.Two strings can become anagram by changing at most k ch
14 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 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 arrays are permutations of each other
Given two unsorted arrays of the same size, write a function that returns true if two arrays are permutations of each other, otherwise false. Examples: Input: arr1[] = {2, 1, 3, 5, 4, 3, 2} arr2[] = {3, 2, 2, 4, 5, 3, 1}Output: YesInput: arr1[] = {2, 1, 3, 5,} arr2[] = {3, 2, 2, 4}Output: NoWe stron
15+ min read
Check if two numbers are bit rotations of each other or not
Given two positive integers x and y (0 < x, y < 2^32), check if one integer is obtained by rotating bits of the other. Bit Rotation: A rotation (or circular shift) is an operation similar to a shift except that the bits that fall off at one end are put back to the other end. Examples: Input :
6 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 if two arrays are equal or not
Given two arrays, a and b of equal length. The task is to determine if the given arrays are equal or not. Two arrays are considered equal if:Both arrays contain the same set of elements.The arrangements (or permutations) of elements may be different.If there are repeated elements, the counts of each
6 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.Method 1 (Use Sorting):Sort bot
6 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