Learning Outcome
Turn the Antenna Combinations Within Distance interview variant into a clear brute-force baseline, optimized pattern, and implementation plan.
Original Interview Statement
Given antenna positions and distance d, count valid pairs or combinations whose difference is less than d.
Examples
| Item | Detail |
|---|---|
| positions=[1,3,5], d=3 | pairs (1,3),(3,5) |
Brute Force Approach
Check every pair or every triple directly.
Optimized Approach
Sort positions and use two pointers. For each right, move left until distance is valid, then add combinations from the window.
Exact Pseudocode
sort a
left = 0
for right in range(n):
while a[right] - a[left] >= d: left += 1
add right-left valid pairs
Reference Code
def count_pairs_within_distance(pos, d):
pos.sort()
left = 0
ans = 0
for right, value in enumerate(pos):
while value - pos[left] >= d:
left += 1
ans += right - left
return ansComplexity
| Item | Detail |
|---|---|
| Brute force | O(n^2) |
| Optimized | O(n log n) sorting plus O(n) |
Edge Cases
- Equal positions
- Strict < d vs <= d
- Need triples instead of pairs
Follow-ups
- Count triples
- Return actual pairs
Nearest Practice References
- Two pointers counting pairs
Common Mistakes
- Copying the nearest LeetCode solution without checking the changed rule.
- Skipping duplicate or boundary cases.
- Not stating the brute force before the optimized approach.