Maximum Hamming Distances - Problem
Maximum Hamming Distances
You're given an array
The Hamming distance between two integers is the number of bit positions where they differ when represented as
Return an array
Example: If
• 4 in binary:
• 14 in binary:
• 2 in binary:
The maximum Hamming distance for 4 is 3 (compared to 14: they differ in 3 positions).
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:
0010The 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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code