Absolute distinct count in a sorted array - GeeksforGeeks

02 Mar, 2022
Given a sorted array of integers, return the number of distinct absolute values among the elements of the array. The input can contain duplicates values. Examples:  
Input: [-3, -2, 0, 3, 4, 5]
Output: 5
There are 5 distinct absolute values
among the elements of this array, i.e.
0, 2, 3, 4 and 5)

Input:  [-1, -1, -1, -1, 0, 1, 1, 1, 1]
Output: 2

Input:  [-1, -1, -1, -1, 0]
Output: 2

Input:  [0, 0, 0]
Output: 1 
The solution should do only one scan of the input array and should not use any extra space. i.e. expected time complexity is O(n) and auxiliary space is O(1). 
One simple solution is to use set. For each element of the input array, we insert its absolute value in the set. As set doesn’t support duplicate elements, the element’s absolute value will be inserted only once. Therefore, the required count is size of the set.Below is the implementation of the idea.  
C++
Java
Python3
C#
Javascript
// C++ program to find absolute distinct// count of an array in O(n) time.#include <bits/stdc++.h>using namespace std; // The function returns number of// distinct absolute values among// the elements of the arrayint distinctCount(int arr[], int n){    unordered_set<int> s;     // Note that set keeps only one    // copy even if we try to insert    // multiple values    for (int i = 0 ; i < n; i++)        s.insert(abs(arr[i]));     return s.size();} // Driver codeint main(){    int arr[] = {-2, -1, 0, 1, 1};    int n = sizeof(arr)/sizeof(arr[0]);     cout << "Count of absolute distinct values : "         << distinctCount(arr, n);     return 0;}
// java code to find absolute distinct// count of an array in O(n) time.import java.util.*; class GFG{    // The function returns number of    // distinct absolute values among    // the elements of the array    static int distinctCount(int arr[], int n)    {        Set<Integer> s = new HashSet<Integer> ();         // Note that set keeps only one        // copy even if we try to insert        // multiple values        for (int i = 0 ; i < n; i++)        s.add(Math.abs(arr[i]));                 return s.size();             }         // Driver code    public static void main(String[] args)    {        int arr[] = {-2, -1, 0, 1, 1};        int n = arr.length;         System.out.println("Count of absolute distinct values : "                           + distinctCount(arr, n));             }} // This code is contributed by prerna saini
# Python3 code to find absolute distinct# count of an array in O(n) time. # This function returns number of# distinct absolute values among# the elements of the arraydef distinctCount(arr, n):    s = set()         # set keeps all unique elements    for i in range(n):        s.add(abs(arr[i]))    return len(s) # Driver Codearr = [-2, -1, 0, 1, 1]n = len(arr)print("Count of absolute distinct values:",                     distinctCount(arr, n)) # This code is contributed# by Adarsh_Verma
     // C# code to find absolute distinct// count of an array in O(n) time.using System;using System.Collections.Generic; class GFG{    // The function returns number of    // distinct absolute values among    // the elements of the array    static int distinctCount(int []arr, int n)    {        HashSet<int> s = new HashSet<int>();         // Note that set keeps only one        // copy even if we try to insert        // multiple values        for (int i = 0 ; i < n; i++)        s.Add(Math.Abs(arr[i]));                 return s.Count;             }         // Driver code    public static void Main()    {        int []arr = {-2, -1, 0, 1, 1};        int n = arr.Length;         Console.Write("Count of absolute distinct values : "                        + distinctCount(arr, n));             }} // This code is contributed by PrinciRaj1992
<script>    // Javascript code to find absolute distinct    // count of an array in O(n) time.         // The function returns number of    // distinct absolute values among    // the elements of the array    function distinctCount(arr, n)    {        let s = new Set();          // Note that set keeps only one        // copy even if we try to insert        // multiple values        for (let i = 0 ; i < n; i++)            s.add(Math.abs(arr[i]));                  return s.size;      }         let arr = [-2, -1, 0, 1, 1];    let n = arr.length;     document.write("Count of absolute distinct values : "                       + distinctCount(arr, n));                            </script>
Output :  
Count of absolute distinct values : 3
Time Complexity : O(n) Auxiliary Space : O(n)The above implementation takes O(n) extra space, how to do in O(1) extra space? The idea is to take advantage of the fact that the array is already Sorted. We initialize the count of distinct elements to number of elements in the array. We start with two index variables from two corners of the array and check for pair in the input array with sum as 0. If pair with 0 sum is found or duplicates are encountered, we decrement the count of distinct elements.Finally we return the updated count.Below is the implementation of above approach. 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find absolute distinct// count of an array using O(1) space.#include <bits/stdc++.h>using namespace std; // The function returns return number// of distinct absolute values// among the elements of the arrayint distinctCount(int arr[], int n){    // initialize count as number of elements    int count = n;    int i = 0, j = n - 1, sum = 0;     while (i < j)    {        // Remove duplicate elements from the        // left of the current window (i, j)        // and also decrease the count        while (i != j && arr[i] == arr[i + 1])            count--, i++;         // Remove duplicate elements from the        // right of the current window (i, j)        // and also decrease the count        while (i != j && arr[j] == arr[j - 1])            count--, j--;         // break if only one element is left        if (i == j)            break;         // Now look for the zero sum pair        // in current window (i, j)        sum = arr[i] + arr[j];         if (sum == 0)        {            // decrease the count if (positive,            // negative) pair is encountered            count--;            i++, j--;        }        else if(sum < 0)            i++;        else            j--;    }     return count;} // Driver codeint main(){    int arr[] = {-2, -1, 0, 1, 1};    int n = sizeof(arr)/sizeof(arr[0]);     cout << "Count of absolute distinct values : "         << distinctCount(arr, n);     return 0;}
// Java program to find absolute distinct// count of an array using O(1) space. import java.io.*; class GFG {          // The function returns return number// of distinct absolute values// among the elements of the arraystatic int distinctCount(int arr[], int n){    // initialize count as number of elements    int count = n;    int i = 0, j = n - 1, sum = 0;     while (i < j)    {        // Remove duplicate elements from the        // left of the current window (i, j)        // and also decrease the count        while (i != j && arr[i] == arr[i + 1])        {            count--;            i++;        }        // Remove duplicate elements from the        // right of the current window (i, j)        // and also decrease the count        while (i != j && arr[j] == arr[j - 1])        {            count--;            j--;        }        // break if only one element is left        if (i == j)            break;         // Now look for the zero sum pair        // in current window (i, j)        sum = arr[i] + arr[j];         if (sum == 0)        {            // decrease the count if (positive,            // negative) pair is encountered            count--;            i++;            j--;        }        else if(sum < 0)            i++;        else            j--;    }     return count;} // Driver code         public static void main (String[] args) {         int arr[] = {-2, -1, 0, 1, 1};    int n = arr.length;     System.out.println ("Count of absolute distinct values : "+             distinctCount(arr, n));                      }}
# Python3 program to find absolute distinct# count of an array using O(1) space. # The function returns return number# of distinct absolute values# among the elements of the arraydef distinctCount(arr, n):     # initialize count as number of elements    count = n;    i = 0; j = n - 1; sum = 0;     while (i < j):                 # Remove duplicate elements from the        # left of the current window (i, j)        # and also decrease the count        while (i != j and arr[i] == arr[i + 1]):            count = count - 1;            i = i + 1;         # Remove duplicate elements from the        # right of the current window (i, j)        # and also decrease the count        while (i != j and arr[j] == arr[j - 1]):            count = count - 1;            j = j - 1;         # break if only one element is left        if (i == j):            break;         # Now look for the zero sum pair        # in current window (i, j)        sum = arr[i] + arr[j];         if (sum == 0):                     # decrease the count if (positive,            # negative) pair is encountered            count = count - 1;            i = i + 1;            j = j - 1;                     else if(sum < 0):            i = i + 1;        else:            j = j - 1;         return count;  # Driver codearr = [-2, -1, 0, 1, 1];n = len(arr); print("Count of absolute distinct values : ",                      distinctCount(arr, n)); # This code is contributed# by Akanksha Rai
//C# program to find absolute distinct// count of an array using O(1) space.using System; class GFG {          // The function returns return number// of distinct absolute values// among the elements of the arraystatic int distinctCount(int []arr, int n){    // initialize count as number of elements    int count = n;    int i = 0, j = n - 1, sum = 0;     while (i < j)    {        // Remove duplicate elements from the        // left of the current window (i, j)        // and also decrease the count        while (i != j && arr[i] == arr[i + 1])        {            count--;            i++;        }        // Remove duplicate elements from the        // right of the current window (i, j)        // and also decrease the count        while (i != j && arr[j] == arr[j - 1])        {            count--;            j--;        }        // break if only one element is left        if (i == j)            break;         // Now look for the zero sum pair        // in current window (i, j)        sum = arr[i] + arr[j];         if (sum == 0)        {            // decrease the count if (positive,            // negative) pair is encountered            count--;            i++;            j--;        }        else if(sum < 0)            i++;        else            j--;    }     return count;} // Driver code         public static void Main () {         int []arr = {-2, -1, 0, 1, 1};    int n = arr.Length;     Console.WriteLine("Count of absolute distinct values : "+            distinctCount(arr, n));             // This code is contributed by inder_verma       }}
<?php// PHP program to find absolute distinct// count of an array using O(1) space. // The function returns return number// of distinct absolute values// among the elements of the arrayfunction distinctCount($arr, $n){    // initialize count as number    // of elements    $count = $n;    $i = 0; $j = $n - 1; $sum = 0;     while ($i < $j)    {        // Remove duplicate elements from the        // left of the current window (i, j)        // and also decrease the count        while ($i != $j && $arr[$i] == $arr[$i + 1])            {$count--; $i++;}         // Remove duplicate elements from the        // right of the current window (i, j)        // and also decrease the count        while ($i != $j && $arr[$j] == $arr[$j - 1])            {$count--; $j--;}         // break if only one element is left        if ($i == $j)            break;         // Now look for the zero sum pair        // in current window (i, j)        $sum = $arr[$i] + $arr[$j];         if ($sum == 0)        {            // decrease the count if (positive,            // negative) pair is encountered            $count--;            $i++; $j--;        }        else if($sum < 0)            $i++;        else            $j--;    }     return $count;} // Driver code$arr = array(-2, -1, 0, 1, 1);$n = sizeof($arr); echo "Count of absolute distinct values : " .                     distinctCount($arr, $n); // This code is contributed// by Akanksha Rai?>
<script>    // Javascript program to find absolute distinct    // count of an array using O(1) space.         // The function returns return number    // of distinct absolute values    // among the elements of the array    function distinctCount(arr, n)    {        // initialize count as number of elements        let count = n;        let i = 0, j = n - 1, sum = 0;         while (i < j)        {            // Remove duplicate elements from the            // left of the current window (i, j)            // and also decrease the count            while (i != j && arr[i] == arr[i + 1])                count--, i++;             // Remove duplicate elements from the            // right of the current window (i, j)            // and also decrease the count            while (i != j && arr[j] == arr[j - 1])                count--, j--;             // break if only one element is left            if (i == j)                break;             // Now look for the zero sum pair            // in current window (i, j)            sum = arr[i] + arr[j];             if (sum == 0)            {                // decrease the count if (positive,                // negative) pair is encountered                count--;                i++, j--;            }            else if(sum < 0)                i++;            else                j--;        }         return count;    }         let arr = [-2, -1, 0, 1, 1];    let n = arr.length;       document.write(    "Count of absolute distinct values : " + distinctCount(arr, n));          </script>
Output : 
Count of absolute distinct values : 3
Time Complexity: O(n) Auxiliary Space: O(1)This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
jit_t
inderDuMCA
princiraj1992
Adarsh_Verma
Akanksha_Rai
divyesh072019
mukesh07
surinderdawra388
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java