Longest Subarray consisting of unique elements from an Array | Python3 program to implement the above approach ; Function to find largest subarray with no duplicates ; Stores index of array elements ; Update j based on previous occurrence of a [ i ] ; Update ans to store maximum length of subarray ; Store the index of current occurrence of a [ i ] ; Return final ans ; Driver Code
from collections import defaultdict NEW_LINE def largest_subarray ( a , n ) : NEW_LINE INDENT index = defaultdict ( lambda : 0 ) NEW_LINE ans = 0 NEW_LINE j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = max ( index [ a [ i ] ] , j ) NEW_LINE ans = max ( ans , i - j + 1 ) NEW_LINE index [ a [ i ] ] = i + 1 NEW_LINE i += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 1 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( largest_subarray ( arr , n ) ) NEW_LINE