Absolute distinct count in a sorted array in C++?

C++Server Side ProgrammingProgramming

An array is a collection of elements of the same data type. A sorted array is an array that has elements stored in a sequence of ascending or descending order.

The distinct count is the number of elements that are not the same.

Absolute distinct count is distinct count of absolute value of the elements i.e. elements without sign(unsigned values).

In this program we will find the absolute distinct count in a sorted array. i.e. we will count the number of distinct values if absolute value of each element of the array is considered.

For example,

Input : [-3 , 0 , 3 , 6 ]
Output : 3

There are 3 distinct absolute values in the array, the elements are 0, 3, and 6.

To solve this we have methods, using different ways.

By using a set 

A set always contains distinct element. so we will check for the absolute values in the set and if it is not available when will add the element to the set. and return the size of the set.

Algorithm −

  • Create a set of same data type as array.

  • Find absolute value of each element and store the elements in the array. The set will store one single value even if multiple values are encountered.

  • After all elements are entered. Return the length of the set. This will give the number of distinct elements is the array.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   int arr[] = {-3, 0, 2, 6};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "Count of absolute distinct values : ";
   unordered_set<int> s;
   for (int i = 0 ; i < n; i++)
      s.insert(abs(arr[i]));
      int nof = s.size();
      cout<<nof;
      return 0;
}

Output

Count of absolute distinct values : 4

Using array check and count variable 

This method uses only a single variable instead of a set. We will give you a count variable to count distinct element of the array.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int arr[] = {-5, -1, 0, 5, 8};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "Count of absolute distinct values : ";
   int count = n;
   int i = 0, j = n - 1, sum = 0;
   while (i < j) {
      while (i != j && arr[i] == arr[i + 1])
         count--, i++;
      while (i != j && arr[j] == arr[j - 1])
         count--, j--;
      if (i == j)
         break;
      sum = arr[i] + arr[j];
      if (sum == 0) {
         count--;
         i++, j--;
      }
      else if(sum < 0)
         i++;
      else
         j--;
   }
   cout<< count;
   return 0;
}

Output

Count of absolute distinct values : 4
raja
Published on 03-Oct-2019 13:16:21
Advertisements