Maximum Hamming Distances - Problem
Maximum Hamming Distances

You're given an array nums of integers and an integer m, where each element nums[i] satisfies 0 <= nums[i] < 2^m. Your task is to find the maximum Hamming distance for each element in the array.

The Hamming distance between two integers is the number of bit positions where they differ when represented as m-bit binary numbers (with leading zeros if necessary).

Return an array answer where answer[i] represents the maximum Hamming distance between nums[i] and any other element in the array.

Example: If nums = [4, 14, 2] and m = 4, then:
• 4 in binary: 0100
• 14 in binary: 1110
• 2 in binary: 0010

The maximum Hamming distance for 4 is 3 (compared to 14: they differ in 3 positions).

Input & Output

example_1.py — Basic Case
$ Input: nums = [4, 14, 2], m = 4
Output: [3, 2, 3]
💡 Note: For 4 (0100): max distance is 3 with 14 (1110). For 14 (1110): max distance is 2 with 2 (0010). For 2 (0010): max distance is 3 with 14 (1110).
example_2.py — Duplicate Numbers
$ Input: nums = [1, 1, 3], m = 2
Output: [2, 2, 2]
💡 Note: For 1 (01): max distance is 2 with 3 (11). For second 1 (01): also 2 with 3 (11). For 3 (11): max distance is 2 with either 1 (01).
example_3.py — Single Element
$ Input: nums = [5], m = 3
Output: [0]
💡 Note: With only one element, there's no other element to compare with, so the maximum Hamming distance is 0.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ m ≤ 20
  • 0 ≤ nums[i] < 2m
  • Each number can be represented using exactly m bits

Visualization

Tap to expand
Maximum Hamming Distance VisualizationExample: nums = [4, 14, 2], m = 4Step 1: Binary Representation4 → 010014 → 11102 → 0010010011100010Step 2: Calculate Hamming DistancesFor number 4 (0100):0110vs 14 (1110) → 3 differences0110vs 2 (0010) → 2 differencesMaximum for 4: 3Step 3: Final Result4 → 314 → 22 → 3Result: [3, 2, 3]💡 Key Insight: Use XOR to find bit differences efficiently, then optimize with frequency maps instead of checking all pairs!
Understanding the Visualization
1
Convert to Binary
Represent each number as an m-bit binary string
2
Compare Bit Positions
For each pair, count positions where bits differ
3
Find Maximum
For each number, identify the other number with maximum differences
4
Optimize with Frequency Map
Use smart complement generation instead of checking all pairs
Key Takeaway
🎯 Key Insight: The maximum Hamming distance problem can be solved efficiently by recognizing that we need to find numbers with the most bit differences. Instead of checking all pairs (O(n²)), we can use frequency counting and systematic complement generation to reduce complexity significantly.
Asked in
Google 42 Amazon 38 Meta 31 Microsoft 25 Apple 18
56.4K Views
Medium-High Frequency
~25 min Avg. Time
1.8K 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