Check if two Integer are anagrams of each other
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: YesInput: 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> |
Yes
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> |
Yes
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)); |
Yes
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" ); } |
Yes
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.