Number of anomalies in an array

Given an array A of N integers. An anomaly is a number for which the absolute difference between it and every other number in the array is greater than K where k is a given positive integer. Find the number of anomalies.

Examples:

Input : arr[] = {1, 3, 5}, k = 1
Output : 3
Explanation:
All the numbers in the array are anamolies because 
For the number 1 abs(1-3)=2, abs(1-5)=4 which all are greater than 1,
For the number 3 abs(3-1)=2, abs(3-5)=2 which all are again greater than 1
For the number 5 abs(5-1)=4, abs(5-3)=2 which all are again greater than 1
So there are 3 anamolies.

Input : arr[] = {7, 1, 8}, k = 5
Output : 1


Simple Approach:
We simply check for each number if it satisfies the condition given condition that is absolute difference is greater than K or not with each of the other number.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A simple C++ solution to count anomalies in
// an array.
#include<iostream>
using namespace std;
  
int countAnomalies(int arr[], int n, int k)
{
   int res = 0;
   for (int i=0; i<n; i++)
   {
      int j; 
      for (j=0; j<n; j++)
         if (i != j && abs(arr[i] - arr[j]) <= k)
              break;
  
      if (j == n)
         res++;
   
   return res;
}
  
int main()
{
   int arr[] = {7, 1, 8}, k = 5;
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << countAnomalies(arr, n, k);
   return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// A simple java solution to count 
// anomalies in an array.
class GFG 
{
static int countAnomalies(int arr[], 
                          int n, int k)
{
    int res = 0;
    for (int i = 0; i < n; i++)
    {
        int j; 
        for (j = 0; j < n; j++)
            if (i != j && Math.abs(arr[i] - 
                                   arr[j]) <= k)
                break;
      
        if (j == n)
            res++;
    
    return res;
}
  
  
// Driver code
public static void main(String args[])
{
    int arr[] = {7, 1, 8}, k = 5;
    int n = arr.length;
    System.out.println(countAnomalies(arr, n, k));
}
}
  
// This code is contributed by ANKITRAI1

chevron_right


Python3

# A simple Python3 solution to
# count anomalies in an array.

def countAnomalies(arr, n, k):

res = 0
for i in range(0, n):

j = 0
while j < n: if i != j and abs(arr[i] - arr[j]) <= k: break j += 1 if j == n: res += 1 return res # Driver Code if __name__ == "__main__": arr = [7, 1, 8] k = 5 n = len(arr) print(countAnomalies(arr, n, k)) # This code is contributed by Rituraj Jain [tabby title="C#"]

filter_none

edit
close

play_arrow

link
brightness_4
code

// A simple C# solution to count 
// anomalies in an array.
using System;
  
class GFG 
{
static int countAnomalies(int[] arr, 
                          int n, int k)
{
    int res = 0;
    for (int i = 0; i < n; i++)
    {
        int j; 
        for (j = 0; j < n; j++)
            if (i != j && Math.Abs(arr[i] - 
                                arr[j]) <= k)
                break;
      
        if (j == n)
            res++;
    
    return res;
}
  
  
// Driver code
public static void Main()
{
    int[] arr = {7, 1, 8};
    int k = 5;
    int n = arr.Length;
    Console.WriteLine(countAnomalies(arr, n, k));
}
}
  
// This code is contributed
// by Akanksha Rai(Abby_akku)

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
// A simple PHP solution to count 
// anomalies in an array.
function countAnomalies(&$arr, $n, $k)
{
    $res = 0;
    for ($i = 0; $i < $n; $i++)
    
        for ($j = 0; $j < $n; $j++)
            if ($i != $j && abs($arr[$i] - 
                                $arr[$j]) <= $k)
                break;
      
        if ($j == $n)
            $res++;
    
    return $res;
}
  
// Driver Code
$arr = array(7, 1, 8);
$k = 5;
$n = sizeof($arr);
echo countAnomalies($arr, $n, $k);
  
// This code is contributed
// by ChitraNayal
?>

chevron_right


Output:

1

Time Complexity: O(n * n)

Efficient Approach using Binary Search
1) Sort the array.
2) For every element, find largest element greater than it and smallest element greater than it. We can find these two in O(Log n) time using Binary Search. If difference with these two elements is more than k, we increment result.

Prerequisites for below C++ code : lower_bound in C++, upper_bound in C++.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<bits/stdc++.h>
using namespace std;
  
int countAnomalies(int a[], int n, int k)
{
  
   // Sort the array so that we can apply binary
   // search.
   sort(a, a+n);
  
   // One by one check every element if it is
   // anomaly or not using binary search.
   int res = 0;
   for (int i=0; i<n; i++)
   {
      int *u = upper_bound(a, a+n, a[i]);
        
      // If arr[i] is not largest element and 
      // element just greater than it is within
      // k, then return false.
      if (u != a+n && ((*u) - a[i]) <= k)
         continue;  
  
      int *s = lower_bound(a, a+n, a[i]);
        
      // If there are more than one occurrences
      // of arr[i], return false. 
      if (u - s > 1)
          continue;
  
      // If arr[i] is not smallest element and
      // just smaller element is not k distance away
      if (s != a && (*(s - 1) - a[i]) <= k)
          continue;
  
      res++;      
   
   return res;
}
  
int main()
{
   int arr[] = {7, 1, 8}, k = 5;
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << countAnomalies(arr, n, k);
   return 0;
}

chevron_right


Output:

1

Time Complexity : O(n Log n)


Another efficient solution for small k

1) Insert all values of array in a hash table.
2) Traverse array again and for every value arr[i], search for every value from arr[i] – k to arr[i] + k (excluding arr[i]). If none of the elements are found, then arr[i] is anomaly.

Time Complexity : O(n k)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.