 Open in App
Not now

# Count all elements in the array which appears at least K times after their first occurrence

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

Given an array arr[] of N integer elements and an integer K. The task is to count all distinct arr[i] such that arr[i] appears at least K times in the index range i + 1 to n – 1.

Examples:

Input: arr[] = {1, 2, 1, 3}, K = 1
Output:
arr = 1 is the only element that appears at least once in the index range [1, 3] i.e. arr

Input: arr[] = {1, 2, 3, 2, 1, 3, 1, 2, 1}, K = 2
Output: 2

Naive Approach: Start from i = 0 to n-1, count occurrences of arr[i] in range i+1 to n-1. If the count is greater or equal to K, increment result by 1. Make a hash array to avoid duplicates.

Below is the implementation of the above approach:

## C++

 `// C++ implementation of the approach` `#include ` `#include ` `using` `namespace` `std;`   `// Function to return the count of` `// all distinct valid elements` `int` `countOccurrence(``int` `n, ``int` `arr[], ``int` `k)` `{` `    ``int` `cnt, ans = 0;`   `    ``// To avoid duplicates` `    ``map<``int``, ``bool``> hash;`   `    ``// Traverse the complete array` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``cnt = 0;`   `        ``// If current element is previously checked` `        ``// don't check it again` `        ``if` `(hash[arr[i]] == ``true``)` `            ``continue``;`   `        ``// To avoid duplicates` `        ``hash[arr[i]] = ``true``;`   `        ``// Count occurrence of arr[i] in range [i + 1, n - 1]` `        ``for` `(``int` `j = i + 1; j < n; j++) {` `            ``if` `(arr[j] == arr[i])` `                ``cnt++;`   `            ``// If count becomes equal to K` `            ``// break the loop` `            ``if` `(cnt >= k)` `                ``break``;` `        ``}`   `        ``// If cnt >= K` `        ``// increment ans by 1` `        ``if` `(cnt >= k)` `            ``ans++;` `    ``}`   `    ``return` `ans;` `}`   `// Driver code` `int` `main()` `{` `    ``int` `arr[] = { 1, 2, 1, 3 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``int` `k = 1;` `    ``cout << countOccurrence(n, arr, k);`   `    ``return` `0;` `}`

## Java

 `// Java implementation of the approach` `import` `java.util.HashMap;`   `class` `GFG` `{`   `    ``// Function to return the count of` `    ``// all distinct valid elements` `    ``public` `static` `int` `countOccurrence(``int` `n, ``int``[] arr, ``int` `k) ` `    ``{` `        ``int` `cnt, ans = ``0``;`   `        ``// To avoid duplicates` `        ``HashMap hash = ``new` `HashMap<>();`   `        ``// Traverse the complete array ` `        ``for` `(``int` `i = ``0``; i < n; i++) ` `        ``{ ` `            ``cnt = ``0``; `   `            ``// If current element is previously checked ` `            ``// don't check it again` `            ``if` `(hash.get(arr[i]) != ``null` `&& hash.get(arr[i]) == ``true``)` `                ``continue``;`   `                ``// To avoid duplicates` `                ``hash.put(arr[i], ``true``);`   `                ``// Count occurrence of arr[i] in range [i + 1, n - 1] ` `                ``for` `(``int` `j = i + ``1``; j < n; j++)` `                ``{ ` `                    ``if` `(arr[j] == arr[i]) ` `                        ``cnt++; `   `                    ``// If count becomes equal to K ` `                    ``// break the loop ` `                    ``if` `(cnt >= k) ` `                    ``break``; ` `                ``} `   `                ``// If cnt >= K ` `                ``// increment ans by 1 ` `                ``if` `(cnt >= k) ` `                    ``ans++; ` `        ``} `   `        ``return` `ans; ` `    ``}` `    `  `    ``// Driver Code` `    ``public` `static` `void` `main(String[] args) ` `    ``{` `        ``int``[] arr = {``1``, ``2``, ``1``, ``3``};` `        ``int` `n = arr.length;` `        ``int` `k = ``1``;` `        ``System.out.println(countOccurrence(n, arr, k));` `    ``}` `}`   `// This code is contributed by` `// sanjeev2552`

## Python3

 `# Python3 implementation of the approach`   `# Function to return the count of` `# all distinct valid elements` `def` `countOccurrence(n, arr, k):`   `    ``cnt, ans ``=` `0``, ``0`   `    ``# To avoid duplicates` `    ``Hash` `=` `dict``()`   `    ``# Traverse the complete array` `    ``for` `i ``in` `range``(n):` `        ``cnt ``=` `0`   `        ``# If current element is previously ` `        ``# checked don't check it again` `        ``if` `(arr[i] ``in` `Hash``.keys()):` `            ``continue`   `        ``# To avoid duplicates` `        ``Hash``[arr[i]] ``=` `1`   `        ``# Count occurrence of arr[i] in ` `        ``# range [i + 1, n - 1]` `        ``for` `j ``in` `range``(i ``+` `1``, n):` `            ``if` `(arr[j] ``=``=` `arr[i]):` `                ``cnt ``+``=` `1`   `            ``# If count becomes equal to K` `            ``# break the loop` `            ``if` `(cnt >``=` `k):` `                ``break`   `        ``# If cnt >= K` `        ``# increment ans by 1` `        ``if` `(cnt >``=` `k):` `            ``ans ``+``=` `1`   `    ``return` `ans`   `# Driver code` `arr ``=` `[``1``, ``2``, ``1``, ``3``]` `n ``=` `len``(arr)` `k ``=` `1` `print``(countOccurrence(n, arr, k))`   `# This code is contributed ` `# by mohit kumar`

## C#

 `// C# implementation of the approach` `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG ` `{ `   `// Function to return the count of ` `// all distinct valid elements ` `public` `static` `int` `countOccurrence(``int` `n, ` `                                 ``int``[] arr, ``int` `k) ` `{ ` `    ``int` `cnt, ans = 0; `   `    ``// To avoid duplicates ` `    ``Dictionary<``int``, ` `               ``Boolean> hash = ``new` `Dictionary<``int``, ` `                                              ``Boolean>();` `                                              `  `    ``// Traverse the complete array ` `    ``for` `(``int` `i = 0; i < n; i++) ` `    ``{ ` `        ``cnt = 0; `   `        ``// If current element is previously checked ` `        ``// don't check it again ` `        ``if` `(hash.ContainsKey(arr[i]) &&` `            ``hash[arr[i]] == ``true``) ` `            ``continue``; `   `            ``// To avoid duplicates ` `            ``hash.Add(arr[i], ``true``); `   `            ``// Count occurrence of arr[i] ` `            ``// in range [i + 1, n - 1] ` `            ``for` `(``int` `j = i + 1; j < n; j++) ` `            ``{ ` `                ``if` `(arr[j] == arr[i]) ` `                    ``cnt++; `   `                ``// If count becomes equal to K ` `                ``// break the loop ` `                ``if` `(cnt >= k) ` `                ``break``; ` `            ``} `   `            ``// If cnt >= K ` `            ``// increment ans by 1 ` `            ``if` `(cnt >= k) ` `                ``ans++; ` `    ``} `   `    ``return` `ans; ` `} `   `// Driver Code ` `public` `static` `void` `Main(String[] args) ` `{ ` `    ``int``[] arr = {1, 2, 1, 3}; ` `    ``int` `n = arr.Length; ` `    ``int` `k = 1; ` `    ``Console.WriteLine(countOccurrence(n, arr, k)); ` `} ` `} `   `// This code is contributed by Rajput-Ji`

## Javascript

 ``

Output:

`1`

Time Complexity: O(n2*log(n))
Auxiliary Space: O(n), where n is the size of the given array.

Efficient Approach: Declare another hash map to store the occurrence of all elements and start from n – 1 to 0. If occurrence[arr[i]] ≥ k then increment the count by 1 otherwise increment occurrence of arr[i] by 1.

Below is the implementation of the above approach:

## C++

 `// C++ implementation of the approach` `#include ` `#include ` `using` `namespace` `std;`   `// Function to return the count of` `// all distinct valid elements` `int` `countOccurrence(``int` `n, ``int` `arr[], ``int` `k)` `{` `    ``int` `cnt, ans = 0;`   `    ``// To avoid duplicates` `    ``map<``int``, ``bool``> hash;`   `    ``// To store the count of arr[i]` `    ``// in range [i + 1, n - 1]` `    ``map<``int``, ``int``> occurrence;`   `    ``for` `(``int` `i = n - 1; i >= 0; i--) {`   `        ``// To avoid duplicates` `        ``if` `(hash[arr[i]] == ``true``)` `            ``continue``;`   `        ``// If occurrence in range i+1 to n becomes` `        ``// equal to K then increment ans by 1` `        ``if` `(occurrence[arr[i]] >= k) {` `            ``ans++;` `            ``hash[arr[i]] = ``true``;` `        ``}`   `        ``// Otherwise increase occurrence of arr[i] by 1` `        ``else` `            ``occurrence[arr[i]]++;` `    ``}`   `    ``return` `ans;` `}`   `// Driver code` `int` `main()` `{` `    ``int` `arr[] = { 1, 2, 1, 3 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``int` `k = 1;` `    ``cout << countOccurrence(n, arr, k);`   `    ``return` `0;` `}`

## Java

 `// Java implementation of the approach` `import` `java.util.HashMap;`   `class` `GFG` `{`   `    ``// Function to return the count of` `    ``// all distinct valid elements` `    ``public` `static` `int` `countOccurrence(``int` `n, ``int``[] arr, ``int` `k)` `    ``{` `        ``int` `ans = ``0``;`   `        ``// To avoid duplicates` `        ``HashMap hash = ``new` `HashMap<>();`   `        ``// To store the count of arr[i]` `        ``// in range [i + 1, n - 1]` `        ``HashMap occurrence = ``new` `HashMap<>();`   `        ``for` `(``int` `i = n-``1``; i>=``0``; i--)` `        ``{` `            `  `            ``// To avoid duplicates` `            ``if` `(hash.get(arr[i]) != ``null` `&& ` `                ``hash.get(arr[i]) == ``true``)` `                ``continue``;` `            `  `            ``// If occurrence in range i+1 to n becomes` `            ``// equal to K then increment ans by 1` `            ``if` `(occurrence.get(arr[i]) != ``null` `&& ` `                ``occurrence.get(arr[i]) >= k)` `            ``{` `                ``ans++;` `                ``hash.put(arr[i], ``true``);` `            ``}`   `            ``// Otherwise increase occurrence of arr[i] by 1` `            ``else` `            ``{` `                ``if` `(occurrence.get(arr[i]) == ``null``)` `                    ``occurrence.put(arr[i], ``1``);` `                ``else` `                ``{` `                    ``int` `temp = occurrence.get(arr[i]);` `                    ``occurrence.put(arr[i], ++temp);` `                ``}` `            ``}` `        ``}`   `        ``return` `ans; ` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String[] args) ` `    ``{` `        ``int``[] arr = {``1``, ``2``, ``1``, ``3``};` `        ``int` `n = arr.length;` `        ``int` `k = ``1``;` `        ``System.out.println(countOccurrence(n, arr, k));` `    ``}` `}`   `// This code is contributed by` `// sanjeev2552`

## Python3

 `# Python3 implementation of the approach `   `# Function to return the count of ` `# all distinct valid elements ` `def` `countOccurrence(n, arr, k) :`   `    ``ans ``=` `0``; `   `    ``# To avoid duplicates ` `    ``hash` `=` `dict``.fromkeys(arr,``0``); `   `    ``# To store the count of arr[i] ` `    ``# in range [i + 1, n - 1] ` `    ``occurrence ``=` `dict``.fromkeys(arr, ``0``); `   `    ``for` `i ``in` `range``(n ``-` `1``, ``-``1``, ``-``1``) :`   `        ``# To avoid duplicates ` `        ``if` `(``hash``[arr[i]] ``=``=` `True``) :` `            ``continue``; `   `        ``# If occurrence in range i+1 to n ` `        ``# becomes equal to K then increment` `        ``# ans by 1 ` `        ``if` `(occurrence[arr[i]] >``=` `k) :` `            ``ans ``+``=` `1``; ` `            ``hash``[arr[i]] ``=` `True``; ` `        `  `        ``# Otherwise increase occurrence ` `        ``# of arr[i] by 1 ` `        ``else` `:` `            ``occurrence[arr[i]] ``+``=` `1``; ` `    `  `    ``return` `ans; `   `# Driver code ` `if` `__name__ ``=``=` `"__main__"` `:`   `    ``arr ``=` `[ ``1``, ``2``, ``1``, ``3` `]; ` `    ``n ``=` `len``(arr) ;` `    ``k ``=` `1``; ` `    ``print``(countOccurrence(n, arr, k)); `   `# This code is contributed by Ryuga`

## C#

 `// C# implementation of the approach` `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG` `{`   `    ``// Function to return the count of` `    ``// all distinct valid elements` `    ``public` `static` `int` `countOccurrence(``int` `n, ` `                                     ``int``[] arr, ` `                                     ``int` `k)` `    ``{` `        ``int` `ans = 0;`   `        ``// To avoid duplicates` `        ``Dictionary<``int``,` `                   ``bool``> hash = ``new` `Dictionary<``int``, ` `                                               ``bool``>();`   `        ``// To store the count of arr[i]` `        ``// in range [i + 1, n - 1]` `        ``Dictionary<``int``,     ` `                   ``int``> occurrence = ``new` `Dictionary<``int``, ` `                                                   ``int``>();` `        `  `        ``for` `(``int` `i = n - 1; i >= 0; i--)` `        ``{` `            `  `            ``// To avoid duplicates` `            ``if` `(hash.ContainsKey(arr[i]) && ` `                ``hash[arr[i]] == ``true``)` `                ``continue``;` `            `  `            ``// If occurrence in range i+1 to n becomes` `            ``// equal to K then increment ans by 1` `            ``if` `(occurrence.ContainsKey(arr[i]) && ` `                ``occurrence[arr[i]] >= k)` `            ``{` `                ``ans++;` `                ``hash.Add(arr[i], ``true``);` `            ``}`   `            ``// Otherwise increase occurrence of arr[i] by 1` `            ``else` `            ``{` `                ``if` `(!occurrence.ContainsKey(arr[i]))` `                    ``occurrence.Add(arr[i], 1);` `                ``else` `                ``{` `                    ``int` `temp = occurrence[arr[i]];` `                    ``occurrence.Add(arr[i], ++temp);` `                ``}` `            ``}` `        ``}` `        ``return` `ans; ` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `Main(String[] args) ` `    ``{` `        ``int``[] arr = {1, 2, 1, 3};` `        ``int` `n = arr.Length;` `        ``int` `k = 1;` `        ``Console.WriteLine(countOccurrence(n, arr, k));` `    ``}` `}`   `// This code is contributed by 29AjayKumar`

## Javascript

 ``

Output:

`1`

Time Complexity: O(n)
Auxiliary Space: O(n), where n is the size of the given array.

My Personal Notes arrow_drop_up
Related Articles