Given an array of sorted integers that may contain several duplicate elements, count the total number of distinct absolute values in it.

For example,

Input:  { -1, -1, 0, 1, 1, 1 }
Output: The total number of distinct absolute values is 2 (0 and 1)
 
 
Input:  { -2, -1, 0, 1, 2, 3 }
Output: The total number of distinct absolute values is 4 (0, 1, 2 and 3)
 
 
Input:  { -1, -1, -1, -1 }
Output: The total number of distinct absolute values is 1 (only 1)

Practice this problem

We can easily solve this problem by inserting the absolute value of each array element into a set. We know that a set doesn’t permit duplicates, and hence its size would be the desired count. This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

The total number of distinct absolute values is 2

Java


Download  Run Code

Output:

The total number of distinct absolute values is 2

Python


Download  Run Code

Output:

The total number of distinct absolute values is 2

The time complexity of the above solution is O(n), where n is the size of the input. It doesn’t take advantage of the fact that the input is already sorted and requires O(n) extra space. We can use the sliding window approach to easily solve this problem in O(1) extra space.

 
The idea is to initialize the distinct count as the total number of elements present in the input. The program checks for a pair with zero-sum with the help of two index variables (initially pointing to two corners of the array). If the pair with zero-sum is found (or duplicates are encountered), decrement the count of distinct elements. Finally, return the updated count.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The total number of distinct absolute values is 2

Java


Download  Run Code

Output:

The total number of distinct absolute values is 2

Python


Download  Run Code

Output:

The total number of distinct absolute values is 2

Author: Aditya Goel