Sometimes, while working with lists, we can have a problem in which we need to find maximum distance between reoccurring elements. This kind of problem can have application in competitive programming and web development domain. Let’s discuss certain way in which this task can be performed.
Method : Using loop +
max() + defaultdict() + enumerate()
The combination of above functions can be used to perform this particular task. In this, we first initialize the temp dict with list using defaultdict(). The iteration is using enumerate() and max() performs the maximum distance between all similar numbers in list.
The original list is : [4, 5, 6, 4, 6, 3] Maximum distance between same element is : 3
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.