Maximum Hamming Distances - Problem

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).

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,1,4,2], m = 3
Output: [3,2,3,3]
💡 Note: For nums[0]=3 (011): max distance is with nums[2]=4 (100), differing in 3 positions. For nums[1]=1 (001): max distance is 2 (with nums[2]=4 or nums[3]=2). For nums[2]=4 (100): max distance is 3 (with nums[0]=3 or nums[3]=2). For nums[3]=2 (010): max distance is 3 (with nums[2]=4).
Example 2 — Small Array
$ Input: nums = [1,0], m = 1
Output: [1,1]
💡 Note: 1 (binary: 1) and 0 (binary: 0) differ in 1 position, so maximum distance for both is 1.
Example 3 — Same Numbers
$ Input: nums = [2,2,2], m = 2
Output: [0,0,0]
💡 Note: All numbers are identical, so Hamming distance between any pair is 0.

Constraints

  • 2 ≤ nums.length ≤ 104
  • 1 ≤ m ≤ 20
  • 0 ≤ nums[i] < 2m

Visualization

Tap to expand
Maximum Hamming Distances INPUT nums = [3, 1, 4, 2], m = 3 3 011 1 001 4 100 2 010 Binary (m=3 bits) Value Binary 3 011 1 001 4 100 2 010 Range: 0 to 2^3-1 = 7 Possible values: 0-7 ALGORITHM STEPS 1 Build Reachability BFS from each number to find max distances 2 Complement Analysis For each nums[i], find ~nums[i] (bit flip) 3 Distance Calculation XOR to find differing bits, count popcount 4 Find Maximum For each element, store max Hamming dist Example: nums[0]=3 3 XOR 4 = 011 XOR 100 = 111 (3 bits) Hamming(3,4) = 3 FINAL RESULT answer = [3, 3, 3, 3] 3 3 3 3 Max Distances Found: nums[i] Max Dist 3 (011) 3 vs 4 1 (001) 3 vs 4 4 (100) 3 vs 3 2 (010) 3 vs 4 OK All elements achieve max distance of 3 Key Insight: The maximum Hamming distance between any nums[i] and other elements can be found by analyzing bit complements. Using BFS/DP from all array elements simultaneously allows O(m * 2^m) preprocessing to find nearest complement patterns for each possible value. TutorialsPoint - Maximum Hamming Distances | Optimized Bit Analysis
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 23
23.4K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen