Open in App
Not now

# Number of anomalies in an array

• Difficulty Level : Easy
• Last Updated : 31 Dec, 2022

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 anomalies 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 anomalies.

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

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

## C++

 `// A simple C++ solution to count anomalies in` `// an array.` `#include` `using` `namespace` `std;`   `int` `countAnomalies(``int` `arr[], ``int` `n, ``int` `k)` `{` `   ``int` `res = 0;` `   ``for` `(``int` `i=0; i

## Java

 `// 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`

## 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`

## C#

 `// 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)`

## PHP

 ``

## Javascript

 ``

Output

`1`

Time Complexity: O(n * n)
Auxiliary Space: O(1)

Efficient Approach using Binary Search

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

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

Implementation:

## C++

 `#include` `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 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;` `}`

## Java

 `import` `java.util.*;`   `class` `GFG ` `{`   `    ``static` `int` `countAnomalies(``int` `a[], ``int` `n, ``int` `k) ` `    ``{`   `        ``// Sort the array so that we can apply binary` `        ``// search.` `        ``Arrays.sort(a);`   `        ``// 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, ``0``, n, a[i]);`   `            ``// If arr[i] is not largest element and` `            ``// element just greater than it is within` `            ``// k, then return false.` `            ``if` `(u < n && a[u] - a[i] <= k)` `                ``continue``;`   `            ``int` `s = lower_bound(a, ``0``, 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 > ``0` `&& a[s - ``1``] - a[i] <= k)` `                ``continue``;`   `            ``res++;` `        ``}` `        ``return` `res;` `    ``}`   `    ``static` `int` `lower_bound(``int``[] a, ``int` `low, ` `                            ``int` `high, ``int` `element)` `    ``{` `        ``while` `(low < high) ` `        ``{` `            ``int` `middle = low + (high - low) / ``2``;` `            ``if` `(element > a[middle])` `                ``low = middle + ``1``;` `            ``else` `                ``high = middle;` `        ``}` `        ``return` `low;` `    ``}`   `    ``static` `int` `upper_bound(``int``[] a, ``int` `low, ` `                            ``int` `high, ``int` `element) ` `    ``{` `        ``while` `(low < high) ` `        ``{` `            ``int` `middle = low + (high - low) / ``2``;` `            ``if` `(a[middle] > element)` `                ``high = middle;` `            ``else` `                ``low = middle + ``1``;` `        ``}` `        ``return` `low;` `    ``}`   `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int` `arr[] = { ``7``, ``1``, ``8` `}, k = ``5``;` `        ``int` `n = arr.length;` `        ``System.out.print(countAnomalies(arr, n, k));` `    ``}` `}`   `// This code is contributed by 29AjayKumar`

## Python3

 `# Python3 program to implement` `# the above approach` `def` `countAnomalies(a, n, k):`   `    ``# Sort the array so that` `    ``# we can apply binary` `    ``# search.` `    ``a ``=` `sorted``(a);`   `    ``# One by one check every ` `    ``# element if it is anomaly ` `    ``# or not using binary search.` `    ``res ``=` `0``;` `    `  `    ``for` `i ``in` `range``(n):` `        ``u ``=` `upper_bound(a, ``0``, ` `                        ``n, a[i]);`   `        ``# If arr[i] is not largest ` `        ``# element and element just ` `        ``# greater than it is within` `        ``# k, then return False.` `        ``if` `(u < n ``and` `            ``a[u] ``-` `a[i] <``=` `k):` `            ``continue``;`   `        ``s ``=` `lower_bound(a, ``0``, ` `                        ``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 > ``0` `and` `            ``a[s ``-` `1``] ``-` `a[i] <``=` `k):` `            ``continue``;`   `        ``res ``+``=` `1``;`   `    ``return` `res;`   `def` `lower_bound(a, low, ` `                ``high, element):` `  `  `    ``while` `(low < high):` `        ``middle ``=` `int``(low ``+` `                 ``int``(high ``-` `low) ``/` `2``);` `        ``if` `(element > a[middle]):` `            ``low ``=` `middle ``+` `1``;` `        ``else``:` `            ``high ``=` `middle;`   `    ``return` `low;`   `def` `upper_bound(a, low, ` `                ``high, element):` `    ``while` `(low < high):` `        ``middle ``=` `int``(low ``+` `                    ``(high ``-` `low) ``/` `2``);` `        ``if` `(a[middle] > element):` `            ``high ``=` `middle;` `        ``else``:` `            ``low ``=` `middle ``+` `1``;`   `    ``return` `low;`   `# Driver code` `if` `__name__ ``=``=` `'__main__'``:` `  `  `    ``arr ``=` `[``7``, ``1``, ``8``]` `    ``k ``=` `5``;` `    ``n ``=` `len``(arr);` `    ``print``(countAnomalies(arr, ` `                         ``n, k));`   `# This code is contributed by shikhasingrajput`

## C#

 `using` `System;`   `class` `GFG{`   `static` `int` `countAnomalies(``int` `[]a, ``int` `n, ``int` `k) ` `{` `    `  `    ``// Sort the array so that we can ` `    ``// apply binary search.` `    ``Array.Sort(a);`   `    ``// 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, 0, n, a[i]);`   `        ``// If arr[i] is not largest element and` `        ``// element just greater than it is within` `        ``// k, then return false.` `        ``if` `(u < n && a[u] - a[i] <= k)` `            ``continue``;`   `        ``int` `s = lower_bound(a, 0, 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 > 0 && a[s - 1] - a[i] <= k)` `            ``continue``;`   `        ``res++;` `    ``}` `    ``return` `res;` `}`   `static` `int` `lower_bound(``int``[] a, ``int` `low, ` `                       ``int` `high, ``int` `element)` `{` `    ``while` `(low < high) ` `    ``{` `        ``int` `middle = low + (high - low) / 2;` `        `  `        ``if` `(element > a[middle])` `            ``low = middle + 1;` `        ``else` `            ``high = middle;` `    ``}` `    ``return` `low;` `}`   `static` `int` `upper_bound(``int``[] a, ``int` `low, ` `                       ``int` `high, ``int` `element) ` `{` `    ``while` `(low < high) ` `    ``{` `        ``int` `middle = low + (high - low) / 2;` `        `  `        ``if` `(a[middle] > element)` `            ``high = middle;` `        ``else` `            ``low = middle + 1;` `    ``}` `    ``return` `low;` `}`   `// Driver code` `public` `static` `void` `Main(String[] args)` `{` `    ``int` `[]arr = { 7, 1, 8 };` `    ``int` `k = 5;` `    ``int` `n = arr.Length;` `    `  `    ``Console.Write(countAnomalies(arr, n, k));` `}` `}`   `// This code is contributed by Amit Katiyar`

## Javascript

 `     `

Output

`1`

Time Complexity: O(n Log n)
Auxiliary Space: O(1)

Another efficient solution for small k

1. Insert all values of the 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
Related Articles