Subarrays with distinct elements doubt.....getiing tle

can u plzz help me to optimize the code

@ynikhil1999 You can use some type of sliding window or two pointer approach to find sum of lengths of contiguous subarrays having all elements distinct. I am giving you a hint:
Consider the array [1,2,3,4]
1.First form a window with all elements distinct. Here all elements are already distinct. So the window is [1,2,3,4]
Now, Sub arrays starting with 1: {1}, {1,2}, {1,2,3}, {1,2,3,4}
Total length of all subarray starting with 1 : 1+2+3+4 which is n x (n+1)/2 where n is the number of distinct
elements in the subarray.
Similarly, subarrays starting with 2: {2}, {2,3}, {2,3,4}
Total length: 1+2+3 which is also n*(n+1)/2
& so on.
Therefore, when length of sub array is n with all elements distinct , total length of all subarrays starting with any first element = n x (n+1)/2.
So use this concept and then try to solve the problem.We first find largest subarray (with distinct elements) starting from first element. We count sum of lengths in this subarray using above formula. For finding next subarray of the distinct element, we increment starting point, i and ending point, j unless (i+1, j) are distinct. If not possible, then we increment i again and move forward the same way.
Hope this helps. :slightly_smiling_face:

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.