Suppose we have a list of numbers called nums, and we have to find the length of the longest contiguous sublist where all its elements are unique.
So, if the input is like nums = [6, 2, 4, 6, 3, 4, 5, 2], then the output will be 5, as the longest list of unique elements is [6, 3, 4, 5, 2].
To solve this, we will follow these steps −
head := 0, dct := a new map
max_dist := 0
for each index i and element num in nums, do
if num is in dct and dct[num] >= head, then
head := dct[num] + 1
dct[num] := i
if i - head + 1 > max_dist, then
max_dist := i - head + 1
return max_dist
Let us see the following implementation to get better understanding −
Example
class Solution:
def solve(self, nums):
head = 0
dct = {}
max_dist = 0
for i, num in enumerate(nums):
if num in dct and dct[num] >= head:
head = dct[num] + 1
dct[num] = i
if i - head + 1 > max_dist:
max_dist = i - head + 1
return max_dist
ob = Solution()
nums = [6, 2, 4, 6, 3, 4, 5, 2]
print(ob.solve(nums))Input
[6, 2, 4, 6, 3, 4, 5, 2]
Output
5