Count all elements in the array which appears at least K times after their first occurrence
Last Updated :
11 Jul, 2025
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: 1
arr[0] = 1 is the only element that appears at least once in the index range [1, 3] i.e. arr[2]
Input: arr[] = {1, 2, 3, 2, 1, 3, 1, 2, 1}, K = 2
Output: 2
[Naive Approach] Using Nested for loops – O(n^2) Time and O(n) Space
To count valid elements efficiently, we iterate from i = 0 to n-1 and track the occurrences of arr[i]
in the range [i+1, n-1]. If an element appears K or more times, we increment the result. While iterating, if the current element has been checked before, skip it to prevent redundant processing.
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the count of
// all distinct valid elements
int countOccurrence(int n, vector<int> arr, int k)
{
int cnt, ans = 0;
// Traverse the complete array
for (int i = 0; i < n; i++) {
cnt = 0;
bool check = false;
// To check current element is previously checked
for(int j=0;j<i;j++){
if(arr[i]==arr[j]){
check = true;
break;
}
}
// If current element is previously checked
// don't check it again
if(check==1) continue;
// 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()
{
vector<int> arr = { 1, 2, 1, 3 };
int n = arr.size();
int k = 1;
cout << countOccurrence(n, arr, k);
return 0;
}
Java
// Java implementation of the approach
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;
// Traverse the complete array
for (int i = 0; i < n; i++)
{
cnt = 0;
boolean check = false;
// To check current element is previously checked
for(int j=0;j<i;j++){
if(arr[i]==arr[j]){
check = true;
break;
}
}
// If current element is previously checked
// don't check it again
if(check==true)
continue;
// 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
Python
# Python3 implementation of the approach
# Function to return the count of
# all distinct valid elements
def countOccurrence(n, arr, k):
cnt, ans = 0, 0
# Traverse the complete array
for i in range(n):
cnt = 0
check = False;
# To check current element is previously checked
for j in range(0,i):
if(arr[i]==arr[j]):
check = True;
break;
# If current element is previously checked
# don't check it again
if(check == True):
continue;
# 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;
// Traverse the complete array
for (int i = 0; i < n; i++)
{
cnt = 0;
// To check current element is previously checked
bool check = false;
for(int j=0;j<i;j++){
if(arr[i]==arr[j]){
check = true;
break;
}
}
// If current element is previously checked
// don't check it again
if(check == true)continue;
// 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
// JavaScript implementation of the approach
// Function to return the count of
// all distinct valid elements
function countOccurrence(n, arr, k)
{
let cnt, ans = 0;
// To avoid duplicates
// Traverse the complete array
for (let i = 0; i < n; i++)
{
cnt = 0;
// To check current element is previously checked
let check = false;
for(let j=0;j<i;j++){
if(arr[i]==arr[j]){
check = true;
break;
}
}
// If current element is previously checked
// don't check it again
if(check == true)continue;
// Count occurrence of arr[i]
// in range [i + 1, n - 1]
for (let 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
let arr = [1, 2, 1, 3];
let n = arr.length;
let k = 1;
console.log(countOccurrence(n, arr, k));
[Better Approach] Using Binary Search – O(n*log(n)) Time and O(1) Space
To efficiently count valid elements, we note that if an element must appear at least K times after its first occurrence, its total frequency should be at least K+1. We first sort the array, enabling binary search for quick frequency lookup. The frequency is determined as (last occurrence index - first occurrence index) + 1. If it meets or exceeds K+1, we increment the count. Finally, we return the total count.
C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
//Function to find count of all elements that occurs
//atleast k times in the array after first occurrence
int countOccurrence(int arr[], int n, int k)
{ int count = 0;
sort(arr,arr+n);//sort array for binary search
for(int i = 0 ; i < n ;i++)
{
//index of first and last occ of arr[i]
int first_index = lower_bound(arr,arr+n,arr[i])- arr;
int last_index = upper_bound(arr,arr+n,arr[i])- arr-1;
i = last_index; // assign i to last_index to avoid counting
// same element multiple time
int fre = last_index-first_index+1;//finding frequency
if(fre >= k+1)
{ // if frequency >= k+1 ,means elements occur atleast k times
//then increase the count by 1
count += 1;
}
}
return count;//return final answer
}
// Drive code
int main()
{
int arr[] = { 1, 2, 1, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 1;
// Function call
cout << countOccurrence( arr, n, k);
return 0;
}
// This Approach is contributed by nikhilsainiofficial546
Java
import java.util.Arrays;
public class Main {
// Function to find count of all elements that occurs
// atleast k times in the array after first occurrence
static int countOccurrence(int[] arr, int n, int k) {
int count = 0;
Arrays.sort(arr); // sort array for binary search
for (int i = 0; i < n; i++) {
// index of first and last occ of arr[i]
int first_index = Arrays.binarySearch(arr, arr[i]);
if (first_index < 0) { // element not found
continue;
}
int last_index = first_index;
while (last_index + 1 < n && arr[last_index + 1] == arr[i]) {
last_index++;
}
i = last_index; // assign i to last_index to avoid counting
// same element multiple time
int fre = last_index - first_index + 1; // finding frequency
if (fre >= k + 1) {
// if frequency >= k+1, means elements occur atleast k times
// then increase the count by 1
count += 1;
}
}
return ++count; // return final answer
}
// Drive code
public static void main(String[] args) {
int[] arr = { 1, 2, 1, 3 };
int n = arr.length;
int k = 1;
// Function call
System.out.println(countOccurrence(arr, n, k));
}
}
Python
# Function to find count of all elements that occur
# at least k times in the array after first occurrence
def countOccurrence(arr, n, k):
count = 0
arr.sort() # sort array for binary search
i = 0
while i < n:
# index of first and last occurrence of arr[i]
first_index = arr.index(arr[i])
last_index = n - arr[::-1].index(arr[i]) - 1
i = last_index # assign i to last_index to avoid counting
# the same element multiple times
fre = last_index - first_index + 1 # finding frequency
# if frequency >= k+1, means elements occur at least k times
# then increase the count by 1
if fre >= k+1:
count += 1
i+=1
return count # return final answer
# Drive code
arr = [1, 2, 1, 3]
n = len(arr)
k = 1
# Function call
print(countOccurrence(arr, n, k))
C#
using System;
class MainClass {
//Function to find count of all elements that occurs
//atleast k times in the array after first occurrence
static int countOccurrence(int[] arr, int n, int k) {
int count = 0;
Array.Sort(arr); //sort array for binary search
for (int i = 0; i < n; i++) {
//index of first and last occ of arr[i]
int first_index = Array.BinarySearch(arr, arr[i]);
if (first_index < 0) { // element not found
continue;
}
int last_index = first_index;
while (last_index + 1 < n && arr[last_index + 1] == arr[i]) {
last_index++;
}
i = last_index; // assign i to last_index to avoid counting
// same element multiple time
int fre = last_index - first_index + 1; //finding frequency
if (fre >= k + 1) {
// if frequency >= k+1, means elements occur atleast k times
// then increase the count by 1
count += 1;
}
}
return ++count; //return final answer
}
//Drive code
public static void Main() {
int[] arr = { 1, 2, 1, 3 };
int n = arr.Length;
int k = 1;
//Function call
Console.WriteLine(countOccurrence(arr, n, k));
}
}
JavaScript
// js equivalent
//Function to find count of all elements that occurs
//atleast k times in the array after first occurrence
function countOccurrence(arr, n, k) {
let count = 0;
//sort array for binary search
arr.sort((a, b) => a - b);
for (let i = 0; i < n; i++) {
//index of first and last occ of arr[i]
let first_index = arr.indexOf(arr[i]);
let last_index = arr.lastIndexOf(arr[i]);
i = last_index; // assign i to last_index to avoid counting
// same element multiple time
let fre = last_index - first_index + 1; //finding frequency
if (fre >= k + 1) {
// if frequency >= k+1 ,means elements occur atleast k times
//then increase the count by 1
count += 1;
}
}
return count; //return final answer
}
// Drive code
let arr = [1, 2, 1, 3];
let n = arr.length;
let k = 1;
// Function call
console.log(countOccurrence(arr, n, k));
[Expected Approach] Using Hash Map – O(n) Time and O(n) Space
To efficiently count valid elements, we use a hash map to store the occurrence of each element while traversing the array from right to left (n-1 to 0). If an element's occurrence reaches K, we increment the count. Otherwise, we update its occurrence in the hash map.
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
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
unordered_map<int, bool> hash;
// To store the count of arr[i]
// in range [i + 1, n - 1]
unordered_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[0]);
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<Integer, Boolean> hash = new HashMap<>();
// To store the count of arr[i]
// in range [i + 1, n - 1]
HashMap<Integer, Integer> 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
Python
# 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
// Javascript implementation of the approach
// Function to return the count of
// all distinct valid elements
function countOccurrence(n, arr, k)
{
let ans = 0;
// To avoid duplicates
let hash = new Map();
// To store the count of arr[i]
// in range [i + 1, n - 1]
let occurrence = new Map();
for(let 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.set(arr[i], true);
}
// Otherwise increase occurrence of arr[i] by 1
else
{
if (occurrence.get(arr[i]) == null)
occurrence.set(arr[i], 1);
else
{
let temp = occurrence.get(arr[i]);
occurrence.set(arr[i], ++temp);
}
}
}
return ans;
}
// Driver Code
let arr = [ 1, 2, 1, 3 ];
let n = arr.length;
let k = 1;
console.log(countOccurrence(n, arr, k))
// This code is contributed by unknown2108
Similar Problems:
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem