Absolute distinct count in a sorted array
Last Updated :
26 Mar, 2023
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.
Algorithm:
Step 1: Define a function named distinctCount which takes two parameters, an array of integers arr[] and an integer n.
Step 2: Declare an empty HashSet named s.
Step 3: Traverse the array arr[] using a for loop from i=0 to i<n.
Step 4: Insert the absolute value of arr[i] in the set s using the add() function.
Step 5: After the for loop, return the size of set s using the size() function.
Below is the implementation of the idea.
C++
#include <bits/stdc++.h>
using namespace std;
int distinctCount( int arr[], int n)
{
unordered_set< int > s;
for ( int i = 0 ; i < n; i++)
s.insert( abs (arr[i]));
return s.size();
}
int 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
import java.util.*;
class GFG
{
static int distinctCount( int arr[], int n)
{
Set<Integer> s = new HashSet<Integer> ();
for ( int i = 0 ; i < n; i++)
s.add(Math.abs(arr[i]));
return s.size();
}
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
def distinctCount(arr, n):
s = set ()
for i in range (n):
s.add( abs (arr[i]))
return len (s)
arr = [ - 2 , - 1 , 0 , 1 , 1 ]
n = len (arr)
print ( "Count of absolute distinct values:" ,
distinctCount(arr, n))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int distinctCount( int []arr, int n)
{
HashSet< int > s = new HashSet< int >();
for ( int i = 0 ; i < n; i++)
s.Add(Math.Abs(arr[i]));
return s.Count;
}
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));
}
}
|
Javascript
<script>
function distinctCount(arr, n)
{
let s = new Set();
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++
#include <bits/stdc++.h>
using namespace std;
int distinctCount( int arr[], int n)
{
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--;
}
return count;
}
int 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
import java.io.*;
class GFG {
static int distinctCount( int arr[], int n)
{
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--;
}
return count;
}
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
def distinctCount(arr, n):
count = n;
i = 0 ; j = n - 1 ; sum = 0 ;
while (i < j):
while (i ! = j and arr[i] = = arr[i + 1 ]):
count = count - 1 ;
i = i + 1 ;
while (i ! = j and arr[j] = = arr[j - 1 ]):
count = count - 1 ;
j = j - 1 ;
if (i = = j):
break ;
sum = arr[i] + arr[j];
if ( sum = = 0 ):
count = count - 1 ;
i = i + 1 ;
j = j - 1 ;
elif ( sum < 0 ):
i = i + 1 ;
else :
j = j - 1 ;
return count;
arr = [ - 2 , - 1 , 0 , 1 , 1 ];
n = len (arr);
print ( "Count of absolute distinct values : " ,
distinctCount(arr, n));
|
C#
using System;
class GFG {
static int distinctCount( int []arr, int n)
{
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--;
}
return count;
}
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));
}
}
|
PHP
<?php
function distinctCount( $arr , $n )
{
$count = $n ;
$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 --;
}
return $count ;
}
$arr = array (-2, -1, 0, 1, 1);
$n = sizeof( $arr );
echo "Count of absolute distinct values : " .
distinctCount( $arr , $n );
?>
|
Javascript
<script>
function distinctCount(arr, n)
{
let count = n;
let 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--;
}
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)
Similar Reads
Absolute distinct count in a Linked List
Given a Linked List consisting of integers, the task is to print the number of distinct absolute values present in the Linked List. Examples: Input: -1 -> -2 -> 0 -> 4 -> 5 -> 8 Output: 6 Explanation: Distinct absolute node values are {0, 1, 2, 4, 5, 8} Input: -1 -> -1 -> -1 -
6 min read
Count 1's in a sorted binary array
Given a binary array arr[] of size n, which is sorted in non-increasing order, count the number of 1's in it. Examples: Input: arr[] = [1, 1, 0, 0, 0, 0, 0]Output: 2Explanation: Count of the 1's in the given array is 2. Input: arr[] = [1, 1, 1, 1, 1, 1, 1]Output: 7 Input: arr[] = [0, 0, 0, 0, 0, 0,
8 min read
Count-based Absolute difference for Array element
Given an array of integers, A[] of size N. For each ith element in the array, calculate the absolute difference between the count of numbers that are to the left of i and are strictly greater than the ith element, and the count of numbers that are to the right of i and are strictly lesser than the i
10 min read
Count Distinct ( Unique ) elements in an array
Given an array arr[] of length N, The task is to count all distinct elements in arr[]. Examples: Input: arr[] = {10, 20, 20, 10, 30, 10}Output: 3Explanation: There are three distinct elements 10, 20, and 30. Input: arr[] = {10, 20, 20, 10, 20}Output: 2 Naïve Approach: Create a count variable and ru
15 min read
Count of Missing Numbers in a sorted array
Given a sorted array arr[], the task is to calculate the number of missing numbers between the first and last element of the sorted array. Examples: Input: arr[] = { 1, 4, 5, 8 } Output: 4 Explanation: The missing integers in the array are {2, 3, 6, 7}. Therefore, the count is 4. Input: arr[] = {5,
9 min read
Count distinct elements in an array in Python
Given an unsorted array, count all distinct elements in it. Examples: Input : arr[] = {10, 20, 20, 10, 30, 10} Output : 3 Input : arr[] = {10, 20, 20, 10, 20} Output : 2 We have existing solution for this article. We can solve this problem in Python3 using Counter method. Approach#1: Using Set() Thi
2 min read
Count of all pairs in an Array with minimum absolute difference
Given an integer array arr[] of size N, the task is to count the total number of distinct pairs having minimum absolute difference. Examples: Input: arr[] = {4, 2, 1, 3} Output: 3 Explanation: The minimum absolute difference between the pairs {1, 2}, {2, 3}, {3, 4} is 1.Input: arr[] = {1, 3, 8, 10,
5 min read
Print all unique elements present in a sorted array
Given a sorted array arr[] of size N, the task is to print all the unique elements in the array. An array element is said to be unique if the frequency of that element in the array is 1. Examples: Input: arr[ ] = {1, 1, 2, 2, 3, 4, 5, 5}Output: 3 4Explanation: Since 1, 2, 5 are occurring more than o
5 min read
Find the count of distinct numbers in a range
Given an array of size N containing numbers only from 0 to 63, and you are asked Q queries regarding it.Queries are as follows: 1 X Y i.e Change the element at index X to Y2 L R i.e Print the count of distinct elements present in between L and R inclusive Examples: Input: N = 7 ar = {1, 2, 1, 3, 1,
15 min read
Count Inversions of an Array
Given an integer array arr[] of size n, find the inversion count in the array. Two array elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j. Note: Inversion Count for an array indicates that how far (or close) the array is from being sorted. If the array is already sorte
15+ min read