Count Pairs formed by Distinct Element Sub-Arrays in Java

Given an array, our task is to find out how many pairs may be created from each potential contiguous sub-array that contains a different integer. The positive numbers in the array range from 0 to n-1, where n is the array's size.

Example 1:

Input:

int a[] = [4, 8, 8, 9]

Output:

The total number of distinct pairs formed by the elements of sub-arrays is 2.

Explanation:

For the given array [4, 8, 8, 9], the sub-arrays that can be formed have (4,8) and (8,9) distinct pairs. Hence, the total number of distinct pairs is 2.

Example 2:

Input:

int a[] = [1, 4, 2, 4, 3, 2]

Output:

The total number of distinct pairs formed by the elements of sub-arrays is 8.

Explanation:

For the given array [1, 4, 2, 4, 3, 2], the sub-arrays that can be formed are [1, 4, 2], [2, 4, 3] and [4, 3, 2]. Hence from those sub-arrays we can easily form the distinct pairs as (1, 4), (1, 2), (4, 2), (2, 4), (2, 3), (4, 3), (4, 2), (3, 2). Hence, the total number of distinct pairs is 8.

Approach: Sliding Window

The sliding window technique can be used in the given approach to keep a window across a contiguous subarray of the given array. Utilizing a Sliding Window for the specified array is the idea. Making ensuring that every element of the sliding window is unique is its main objective. To mark items in the current window, let's use a window covering that runs from index left to index right and a Boolean array visited. The principle is that each element within the window is unique, and it the window is consistent. Until every element is unique once more, we continue to extend the window to the right. If a duplicate is discovered, we then decrease the window from the left.

As we go, we update the number of pairs in the current window. A particular result demonstrated that the number of pairs in an expanding window may be increased by a factor of one or the window size minus one. The index left is where the window begins, and the index right is where it closes.

Implementation:

FileName: CountPairsFromSubarrays.java

Output:

The total number of distinct pairs formed by the elements of sub-arrays is 8

Complexity Analysis:

The time complexity is O(N^2), where 'N' represents the size of the given array. The space complexity is O(N) since the items of the current window are being marked using the visited array.