Problem:
Given an array of elements, return the length of the longest sub-array where all its elements are distinct.
For example, given the array [5, 1, 3, 5, 2, 3, 4, 1], return 5 as the longest sub-array of distinct elements is [5, 2, 3, 4, 1].
# Python 3 program to get the
# length of the longest subarray where all its elements are distinct.
def numberOfdistincts(array, n):
if n == 0 or n == 1:
return n
# Dictionary to store every element of array
map = {i : 0 for i in array}
# counter to count distinct elements in the array
distintItems = 0
for i in range(n):
if map[array[i]] == 0:
distintItems += 1
map[array[i]] = 1
return distintItems
array = [5, 1, 3, 5, 2, 3, 4, 1]
length = len(array)
distincts = numberOfdistincts(array, length)
print("Number of distinct elements in the longest sub array: "+str(distincts))
This problem was asked by Google.