Find Maximum Distance Between Identical Elements in Python
Compute the maximum index distance between any two identical elements in a list using a dictionary to track first occurrences.
Python code
24 linesfrom collections import defaultdict
def max_distance_between_identical(nums):
first_occurrence = {}
max_dist = 0
for i, num in enumerate(nums):
if num in first_occurrence:
dist = i - first_occurrence[num]
max_dist = max(max_dist, dist)
else:
first_occurrence[num] = i
return max_dist
if __name__ == "__main__":
# Example test cases
test1 = [1, 2, 3, 1, 2, 3, 1]
test2 = [1, 1, 1, 1]
test3 = [1, 2, 3]
print(f"Max distance in {test1}: {max_distance_between_identical(test1)}")
print(f"Max distance in {test2}: {max_distance_between_identical(test2)}")
print(f"Max distance in {test3}: {max_distance_between_identical(test3)}")
Output
Max distance in [1, 2, 3, 1, 2, 3, 1]: 6
Max distance in [1, 1, 1, 1]: 3
Max distance in [1, 2, 3]: 0
How it works
The algorithm uses a dictionary to store the first occurrence index of each distinct value. For every later occurrence, it computes the distance from the first occurrence and updates the maximum. Because each element is processed once and dictionary lookups are O(1), this runs in O(n) time and O(n) space. The solution correctly returns 0 when no duplicates exist.
Common mistakes
- Initializing max_dist to -1 when the problem expects 0 for no duplicates.
- Using a list to track occurrence indices leading to O(n²) time.
- Updating the first occurrence index on every encounter instead of only on the first.
Variations
- Use a defaultdict(list) to store all indices, then compute max difference for each list.
- Compute the last occurrence dictionary and take max of last-first for each unique value.
Real-world use cases
- Identifying the longest gap between repeated user actions in analytics logs to detect engagement patterns.
- Finding the maximum distance between duplicate IP addresses in network traffic to spot suspicious behavior.
- Checking dataset quality by evaluating the span of repeated categorical values in time-series data.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.