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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 12 views 0 copies

Python code

24 lines
Python 3.9+
from 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

stdout
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

  1. Use a defaultdict(list) to store all indices, then compute max difference for each list.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.