Python Dictionary | Check if binary representations of two numbers are anagram
Given two numbers, the task is to check whether their binary representations are anagrams of each other or not. Two binary numbers are said to be anagrams if they contain the same number of 0s and 1s, irrespective of their order.
Example:
Input: a = 8, b = 4
Output: Yes
Explanation:
- Binary representation of 8: 1000
- Binary representation of 4: 0100
- Both contain three 0s and one 1, hence they are anagrams.
Using Bitwise Operations
This is the most efficient method as it works directly on bit counts without converting to large strings.
a, b = 8, 4
b1 = bin(a).count('1')
b2 = bin(b).count('1')
x = max(a.bit_length(), b.bit_length())
c1 = x - b1
c2 = x - b2
if b1 == b2 and c1 == c2:
print("Yes")
else:
print("No")
Output
Yes
Explanation:
- bin(a).count('1'): counts number of 1s in binary form.
- bit_length(): gives the number of bits required to represent the number.
- 0s are found indirectly as total bits minus 1s.
- If both have equal counts of 0s and 1s, their binaries are anagrams.
Using zfill() and Counting Bits
First convert both numbers into 32-bit binary strings using zfill(), then count the number of 0s and 1s in each.
a, b = 8, 4
b1 = bin(a)[2:].zfill(32)
b2 = bin(b)[2:].zfill(32)
c1 = [b1.count('0'), b1.count('1')]
c2 = [b2.count('0'), b2.count('1')]
if c1 == c2:
print("Yes")
else:
print("No")
Output
Yes
Explanation:
- bin() converts the given integer into binary strings.
- [2:] removes the '0b' prefix from the binary strings.
- .zfill(32) pads zeros on the left, ensuring equal length (32 bits).
- [b1.count('0') and b1.count('1')]: count 0s and 1s and create a list.
- If both the lists matches then binaries are anagrams.
Using collections.Counter and Dictionary Comparison
This approach uses the Counter class from Python’s collections module to count the frequency of 0s and 1s, and then compares the two resulting dictionaries.
from collections import Counter
a, b = 8, 4
b1 = bin(a)[2:]
b2 = bin(b)[2:]
pad = abs(len(b1) - len(b2))
if len(b1) > len(b2):
b2 = '0' * pad + b2
else:
b1 = '0' * pad + b1
c1 = Counter(b1)
c2 = Counter(b2)
if c1 == c2:
print("Yes")
else:
print("No")
Output
Yes
Explanation:
- bin(a)[2:], bin(b)[2:]: binary strings without '0b'.
- '0' * pad + b2: adds zeros to equalize lengths.
- Counter(): creates frequency maps of 0s and 1s.
- Equal counters: binaries are anagrams.