First element occurring k times in an array
Last Updated :
26 Jun, 2024
Given an array arr[] of size n, the task is to find the first element that occurs k times. If no element occurs k times, print -1. If multiple elements occur k times, the first one in the array should be the answer.
Examples:
Input: arr = [1,7,4,3,4,8,7], k=2
Output: 7
Explanation: Both 7 and 4 occur 2 times. But 7 is the first that occurs 2 times.
Input: arr = [4,1,6,1,6,4], k=1
Output: -1
Explanation: No element occurs exactly once.
Approaches to find the first element occurring k times in an array:
[Naive Approach] Using Two Nested Loops - O(n2) time and O(1) auxiliary space:
The very basic approach is to use two nested loops to count the occurrences of each element and then determining if it meets the criteria of occurring k times. If an element's count equals k, return it. If no element meets the criteria, return -1.
Code Implementation:
C++
// C++ implementation to find first
// element occurring k times
#include <bits/stdc++.h>
using namespace std;
// Function to find the first element
// occurring k number of times
int firstElement(int arr[], int n, int k)
{
// This loop is used for selection
// of elements
for (int i = 0; i < n; i++) {
// Count how many time selected element
// occurs
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j])
count++;
}
// Check, if it occurs k times or not
if (count == k)
return arr[i];
}
return -1;
}
// Driver Code
int main()
{
int arr[] = { 1, 7, 4, 3, 4, 8, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;
cout << firstElement(arr, n, k);
return 0;
}
Java
public class GFG {
// Java implementation to find first
// element occurring k times
// Function to find the first element
// occurring k number of times
public static int firstElement(int[] arr, int n, int k)
{
// This loop is used for selection
// of elements
for (int i = 0; i < n; i++) {
// Count how many time selected element
// occurs
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
// Check, if it occurs k times or not
if (count == k) {
return arr[i];
}
}
return -1;
}
// Driver Code
public static void main(String[] args)
{
int[] arr = { 1, 7, 4, 3, 4, 8, 7 };
int n = arr.length;
int k = 2;
System.out.print(firstElement(arr, n, k));
}
}
Python
# Python3 implementation to
# find first element
# occurring k times
# function to find the
# first element occurring
# k number of times
def firstElement(arr, n, k):
# dictionary to count
# occurrences of
# each element
for i in arr:
count=0
for j in arr:
if i==j:
count=count+1
if count == k:
return i
# no element occurs k times
return -1
# Driver Code
if __name__=="__main__":
arr = [1, 7, 4, 3, 4, 8, 7];
n = len(arr)
k = 2
print(firstElement(arr, n, k))
C#
// C# implementation to find first
// element occurring k times
using System;
public class GFG {
// Function to find the first element
// occurring k number of times
public static int firstElement(int[] arr, int n, int k)
{
// This loop is used for selection
// of elements
for (int i = 0; i < n; i++) {
// Count how many time selected element
// occurs
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
// Check, if it occurs k times or not
if (count == k) {
return arr[i];
}
}
return -1;
}
// Driver Code
public static void Main(String[] args)
{
int[] arr = { 1, 7, 4, 3, 4, 8, 7 };
int n = arr.Length;
int k = 2;
Console.Write(firstElement(arr, n, k));
}
}
JavaScript
class GFG
{
// javascript implementation to find first
// element occurring k times
// Function to find the first element
// occurring k number of times
static firstElement(arr, n, k)
{
// This loop is used for selection
// of elements
for (var i = 0; i < n; i++)
{
// Count how many time selected element
// occurs
var count = 0;
for (var j=0; j < n; j++)
{
if (arr[i] == arr[j])
{
count++;
}
}
// Check, if it occurs k times or not
if (count == k)
{
return arr[i];
}
}
return -1;
}
// Driver Code
static main(args)
{
var arr = [1, 7, 4, 3, 4, 8, 7];
var n = arr.length;
var k = 2;
console.log(GFG.firstElement(arr, n, k));
}
}
GFG.main([]);
Time complexity: O(n2).
Auxiliary space: O(1) as it is using constant space for variables
[Expected Approach] Using Hashing - O(n) time and O(n) auxiliary space:
To optimize the solution, we can use a hash map to count the occurrences of each element. First traverse the array and store the count of each element in a map then traverse the array again to find the first element with a count equal to k. If no element meets the criteria, return -1.
Code Implementation:
C++
// C++ implementation to find first
// element occurring k times
#include <bits/stdc++.h>
using namespace std;
// function to find the first element
// occurring k number of times
int firstElement(int arr[], int n, int k)
{
// unordered_map to count
// occurrences of each element
unordered_map<int, int> count_map;
for (int i=0; i<n; i++)
count_map[arr[i]]++;
for (int i=0; i<n; i++)
// if count of element == k ,then
// it is the required first element
if (count_map[arr[i]] == k)
return arr[i];
// no element occurs k times
return -1;
}
// Driver program to test above
int main()
{
int arr[] = {1, 7, 4, 3, 4, 8, 7};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;
cout << firstElement(arr, n, k);
return 0;
}
Java
import java.util.HashMap;
// Java implementation to find first
// element occurring k times
class GFG {
// function to find the first element
// occurring k number of times
static int firstElement(int arr[], int n, int k) {
// unordered_map to count
// occurrences of each element
HashMap<Integer, Integer> count_map = new HashMap<>();
for (int i = 0; i < n; i++) {
int a = 0;
if(count_map.get(arr[i])!=null){
a = count_map.get(arr[i]);
}
count_map.put(arr[i], a+1);
}
//count_map[arr[i]]++;
for (int i = 0; i < n; i++) // if count of element == k ,then
// it is the required first element
{
if (count_map.get(arr[i]) == k) {
return arr[i];
}
}
// no element occurs k times
return -1;
}
// Driver program to test above
public static void main(String[] args) {
int arr[] = {1, 7, 4, 3, 4, 8, 7};
int n = arr.length;
int k = 2;
System.out.println(firstElement(arr, n, k));
}
}
Python
# Python3 implementation to
# find first element
# occurring k times
# function to find the
# first element occurring
# k number of times
def firstElement(arr, n, k):
# dictionary to count
# occurrences of
# each element
count_map = {};
for i in range(0, n):
if(arr[i] in count_map.keys()):
count_map[arr[i]] += 1
else:
count_map[arr[i]] = 1
i += 1
for i in range(0, n):
# if count of element == k ,
# then it is the required
# first element
if (count_map[arr[i]] == k):
return arr[i]
i += 1
# no element occurs k times
return -1
# Driver Code
if __name__=="__main__":
arr = [1, 7, 4, 3, 4, 8, 7];
n = len(arr)
k = 2
print(firstElement(arr, n, k))
C#
// C# implementation to find first
// element occurring k times
using System;
using System.Collections.Generic;
class GFG
{
// function to find the first element
// occurring k number of times
static int firstElement(int []arr, int n, int k)
{
// unordered_map to count
// occurrences of each element
Dictionary<int, int> count_map = new Dictionary<int,int>();
for (int i = 0; i < n; i++)
{
int a = 0;
if(count_map.ContainsKey(arr[i]))
{
a = count_map[arr[i]];
count_map.Remove(arr[i]);
count_map.Add(arr[i], a+1);
}
else
count_map.Add(arr[i], 1);
}
//count_map[arr[i]]++;
for (int i = 0; i < n; i++) // if count of element == k ,then
// it is the required first element
{
if (count_map[arr[i]] == k)
{
return arr[i];
}
}
// no element occurs k times
return -1;
}
// Driver code
public static void Main(String[] args)
{
int []arr = {1, 7, 4, 3, 4, 8, 7};
int n = arr.Length;
int k = 2;
Console.WriteLine(firstElement(arr, n, k));
}
}
JavaScript
// JavaScript implementation to find first
// element occurring k times
// Function to find the first element
// occurring k number of times
function firstElement(arr, k) {
// Map to count occurrences of each element
let countMap = new Map();
// Count occurrences of each element
for (let i = 0; i < arr.length; i++) {
if (countMap.has(arr[i])) {
countMap.set(arr[i], countMap.get(arr[i]) + 1);
} else {
countMap.set(arr[i], 1);
}
}
// Find the first element with count equal to k
for (let i = 0; i < arr.length; i++) {
if (countMap.get(arr[i]) === k) {
return arr[i];
}
}
// No element occurs k times
return -1;
}
// Driver code to test above function
let arr = [1, 7, 4, 3, 4, 8, 7];
let k = 2;
console.log(firstElement(arr, k));
Time Complexity: O(n)
Auxiliary Space: O(n) because we are using an auxiliary array of size n to store the count
Similar Reads
Sum of all elements repeating 'k' times in an array Given an array, we have to find the sum of all the elements repeating k times in an array. We need to consider every repeating element just once in the sum. Examples: Input : arr[] = {2, 3, 9, 9} k = 1 Output : 5 2 + 3 = 5 Input : arr[] = {9, 8, 8, 8, 10, 4} k = 3 Output : 8 One simple solution is t
8 min read
Find the Kth occurrence of an element in a sorted Array Given a sorted array arr[] of size N, an integer X, and a positive integer K, the task is to find the index of Kth occurrence of X in the given array. Examples: Input: N = 10, arr[] = [1, 2, 3, 3, 4, 5, 5, 5, 5, 5], X = 5, K = 2Output: Starting index of the array is '0' Second occurrence of 5 is at
15+ min read
Top K Frequent Elements in an Array Given an array arr[] and a positive integer k, the task is to find the k most frequently occurring elements from a given array.Note: If more than one element has same frequency then prioritise the larger element over the smaller one.Examples: Input: arr= [3, 1, 4, 4, 5, 2, 6, 1], k = 2Output: [4, 1]
15+ min read
Unique element in an array where all elements occur k times except one Given an array that contains all elements occurring k times, but one occurs only once. Find that unique element.Examples: Input : arr[] = {6, 2, 5, 2, 2, 6, 6} k = 3Output : 5Explanation: Every element appears 3 times accept 5. Input : arr[] = {2, 2, 2, 10, 2} k = 4Output: 10Explanation: Every eleme
13 min read
Remove an occurrence of most frequent array element exactly K times Given an array arr[], the task is to remove an occurrence of the most frequent array element exactly K times. If multiple array elements have maximum frequency, remove the smallest of them. Print the K deleted elements. Examples: Input: arr[] = {1, 3, 2, 1, 4, 1}, K = 2Output: 1 1Explanation: The fr
12 min read