Input: N = 2, arr = {3,3}
Output: 1
Explanation: All subarrays of the arr are {3}, {3,3}, {3} have values 0, 1, 0 respectively, so the answer is 1.
Input: N = 4, arr = {1, 2, 1, 2}
Output: 4
Explanation: All subarrays of the arr are {1},{1,2},{1,2,1},{1,2,1,2},{2},{2,1},{2,1,2},{1},{1,2},{2} have values 0,0,1,2,0,0,1,0,0,0 respectively, so answer is 4.
To avoid considering all possible subarrays, we can use below approach:
We can first create a map that stores the positions of each distinct element in the array. Then, for each distinct element, we calculate the contribution of subarrays that contain this element. This avoids the need to iterate through all subarrays explicitly.