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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In 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
4 min read
Sorting Algorithms A 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