Maximum Hamming Distances Problem
Description
LeetCode Problem 3141.
Given an array nums and an integer m, with each element nums[i] satisfying 0 <= nums[i] < 2^m, return an array answer. The answer array should be of the same length as nums, where each element answer[i] represents the maximum Hamming distance between nums[i] and any other element nums[j] in the array.
The Hamming distance between two binary integers is defined as the number of positions at which the corresponding bits differ (add leading zeroes if needed).
Example 1:
Input: nums = [9,12,9,11], m = 4
Output: [2,3,2,3]
Explanation:
The binary representation of nums = [1001,1100,1001,1011].
The maximum hamming distances for each index are:
- nums[0]: 1001 and 1100 have a distance of 2.
- nums[1]: 1100 and 1011 have a distance of 3.
- nums[2]: 1001 and 1100 have a distance of 2.
- nums[3]: 1011 and 1100 have a distance of 3.
Example 2:
Input: nums = [3,4,6,10], m = 4
Output: [3,3,2,3]
Explanation:
The binary representation of nums = [0011,0100,0110,1010].
The maximum hamming distances for each index are:
- nums[0]: 0011 and 0100 have a distance of 3.
- nums[1]: 0100 and 0011 have a distance of 3.
- nums[2]: 0110 and 1010 have a distance of 2.
- nums[3]: 1010 and 0100 have a distance of 3.
Constraints:
1 <= m <= 172 <= nums.length <= 2^m0 <= nums[i] < 2^m
Solution
Approach: Reverse Thinking + Multi-source BFS
The farthest element from x is the closest element to the complement of x, because the distance to the complement is m minus the distance to x.
So run a BFS over all 2^m bit patterns: start from every value in nums at distance 0 and, in each round, flip one bit of every pattern in the frontier, assigning the round number to unvisited patterns. This gives dist[y], the Hamming distance from y to the nearest element of nums.
For each x in nums, the answer is m - dist[x ^ (2^m - 1)].
Complexity: time O(m * 2^m), space O(2^m).
class Solution:
def maxHammingDistances(self, nums: List[int], m: int) -> List[int]:
dist = [-1] * (1 << m)
for x in nums:
dist[x] = 0
q = nums
k = 1
while q:
t = []
for x in q:
for i in range(m):
y = x ^ (1 << i)
if dist[y] == -1:
t.append(y)
dist[y] = k
q = t
k += 1
return [m - dist[x ^ ((1 << m) - 1)] for x in nums]