The Wayback Machine - https://web.archive.org/web/20240914153415/https://www.geeksforgeeks.org/first-element-occurring-k-times-array/
Open In App

First element occurring k times in an array

Last Updated : 26 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Easy
49.87%
10.4K

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([]);

Output
7

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));

Output
7

Time Complexity: O(n)
Auxiliary Space: O(n) because we are using an auxiliary array of size n to store the count



Similar Reads

Find GCD of most occurring and least occurring elements of given Array
Given an array arr[] of size n, The task is to find the GCD of the highest and lowest frequency element in the given array. Examples: Input: arr[] = {2, 2, 4, 4, 5, 5, 6, 6, 6, 6}Output: 2Explanation: The frequency of the elements in the above array is freq(2) = 2, freq(4) = 2, freq(5) = 2, freq(6) = 4, The minimum frequency is 2 (of elements 2, 4,
7 min read
Last element of an array after repeatedly removing the first element and appending it to the end of the array twice exactly K times
Given an array arr[] consisting of N integers and a positive integer K, the task is to find the last element present in the array obtained by repeatedly removing the first element of the array and appending it twice to the end of the array K times. Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 5Output: 5Explanation:Initially, the array is {1, 2, 3,
7 min read
Sum of all numbers formed having 4 atmost X times, 5 atmost Y times and 6 atmost Z times
Given three integers X, Y and Z, the task is to find the sum of all the numbers formed having 4 at most X times, 5 at most Y times, and 6 at most Z times, under mod 10^9+7.Examples: Input: X = 1, Y = 1, Z = 1 Output: 3675 Explanation: 4 + 5 + 6 + 45 + 54 + 56 + 65 + 46 + 64 + 456 + 465 + 546 + 564 + 645 + 654 = 3675 Input: X = 4, Y = 5, Z = 6 Outpu
9 min read
Two odd occurring elements in an array where all other occur even times
Given an array where all elements appear even number of times except two, print the two odd occurring elements. It may be assumed that the size of array is at-least two. Examples: Input : arr[] = {2, 3, 8, 4, 4, 3, 7, 8} Output : 2 7 Input : arr[] = {15, 10, 10, 50 7, 5, 5, 50, 50, 50, 50, 50} Output : 7 15 Simple solution : Approach : A simple sol
15+ min read
GCD of elements occurring Fibonacci number of times in an Array
Given an array arr[] containing N elements, the task is to find the GCD of the elements which have frequency count which is a Fibonacci number in the array.Examples: Input: arr[] = { 5, 3, 6, 5, 6, 6, 5, 5 } Output: 3 Explanation : Elements 5, 3, 6 appears 4, 1, 3 times respectively. Hence, 3 and 6 have Fibonacci frequencies. So, gcd(3, 6) = 1Input
8 min read
Find all array elements occurring more than ⌊N/3⌋ times
Given an array arr[] consisting of N integers, the task is to find all the array elements which occurs more than floor (n/3) times. Examples: Input: arr[] = {5, 3, 5}Output: 5Explanation:The frequency of 5 is 2, which is more than N/3(3/3 = 1). Input: arr[] = {7, 7, 7, 3, 4, 4, 4, 5}Output: 4 7Explanation:The frequency of 7 and 4 in the array is 3,
15+ min read
Print all array elements occurring at least M times
Given an array arr[] consisting of N integers and a positive integer M, the task is to find the number of array elements that occur at least M times. Examples: Input: arr[] = {2, 3, 2, 2, 3, 5, 6, 3}, M = 2Output: 2 3Explanation:In the given array arr[], the element that occurs at least M number of times are {2, 3}. Input: arr[] = {1, 32, 2, 1, 33,
15 min read
Count distinct sequences obtained by replacing all elements of subarrays having equal first and last elements with the first element any number of times
Given an array arr[] consisting of N integers, the task is to find the number of different sequences that can be formed after performing the below operation on the given array arr[] any number of times. Choose two indices i and j such that arr[i] is equal to arr[j] and update all the elements in the range [i, j] in the array to arr[i]. Examples: In
7 min read
Count substrings with each character occurring at most k times
Given a string S. Count number of substrings in which each character occurs at most k times. Assume that the string consists of only lowercase English alphabets. Examples: Input : S = ab k = 1 Output : 3 All the substrings a, b, ab have individual character count less than 1. Input : S = aaabb k = 2 Output : 12 Substrings that have individual chara
15+ min read
Check if max occurring character of one string appears same no. of times in other
Given two strings, we need to take the character which has the maximum occurrence in the first string, and then we have to check if that particular character is present in the second string the same number of times as it is present in the first string.Examples: Input : s1 = "sssgeek", s2 = "geeksss" Output : Yes Max occurring character in s1 is 's'
7 min read
Smallest number whose sum of digits is N and every digit occurring at most K times
Given two positive integers N and K, the task is to find the smallest number whose sum of digits is N and every distinct digit in that number occurs at most K times. If no such number exists, print "-1". Examples: Input: N = 25, K = 3Output: 799Explanation: Sum of digits of the number = (7 + 9 + 9) = 25 and is the smallest possible. Input: N =100,
15+ min read
Count M-length substrings occurring exactly K times in a string
Given a string S of length N and two integers M and K, the task is to count the number of substrings of length M occurring exactly K times in the string S. Examples: Input: S = "abacaba", M = 3, K = 2Output: 1Explanation: All distinct substrings of length 3 are "aba", "bac", "aca", "cab".Out of all these substrings, only "aba" occurs twice in the s
15+ min read
Print all words occurring in a sentence exactly K times
Given a string S consisting of lowercase alphabets and an integer K, the task is to print all the words that occur K times in the string S. Examples: Input: S = "banana is in yellow and sun flower is also in yellow", K = 2Output: "is" "yellow" "in"Explanation: The words "is", "yellow" and "in" occurs in the string twice. Input: S = "geeks for geeks
13 min read
Number of substrings with each character occurring even times
Given a string S consisting of N lowercase alphabets, the task is to count the number of substrings whose frequency of each character is even. Examples: Input: S = "abbaa"Output: 4Explanation:The substrings having frequency of each character is even are {"abba", "aa", "bb", "bbaa"}.Therefore, the count is 4. Input: S = "geeksforgeeks"Output: 2 Brut
14 min read
Find the Number Occurring Odd Number of Times
Given an array of positive integers. All numbers occur an even number of times except one number which occurs an odd number of times. Find the number in O(n) time &amp; constant space. Examples : Input : arr = {1, 2, 3, 2, 3, 1, 3}Output : 3 Input : arr = {5, 7, 2, 7, 5, 2, 5}Output : 5 Recommended PracticeParty of CouplesTry It!Find the Number Occ
12 min read
Maximize first element of Array by deleting first or adding a previously deleted element
Given an array arr[] of size N, and an integer K, the task is to maximize the first element of the array in K operations where in each operation: If the array is not empty, remove the topmost element of the array.Add any one of the previously removed element back at the starting of the array. Examples: Input: arr[] = [5, 2, 2, 4, 0, 6], K = 4Output
7 min read
Find Kth most occurring element in an Array
Given an array of integers arr[] of size N and a number K, the task is to find the Kth most occurring element in this array.Note: If there are more than one numbers in the array with the same frequency, then both are considered to be at the same level of occurrence. Therefore print both the numbers. Examples: Input: arr[] = {1, 2, 2, 2, 4, 4, 4, 5,
11 min read
Sum of all even occurring element in an array
Given an array of integers containing duplicate elements. The task is to find the sum of all even occurring elements in the given array. That is the sum of all such elements whose frequency is even in the array. Examples: Input : arr[] = {1, 1, 2, 2, 3, 3, 3}Output : 6The even occurring element are 1 and 2 (both occur two times). Therefore sum of a
12 min read
Maximize first array element by performing given operations at most K times
Given an array arr[] of size N an integer K, the task is to find the maximize the first element of the array by performing the following operations at most K times: Choose a pair of indices i and j (0 ? i, j ? N-1) such that |i ? j| = 1 and arri &gt; 0.Set arri = arri ? 1 and arrj = arrj + 1 on those two indices. Examples: Input: arr[ ] = {1, 0, 3,
7 min read
Count of palindromic strings of size upto N consisting of first K alphabets occurring at most twice
Given two integers N and K, the task is to find the number of palindromic strings of size at most N consisting of the first K lowercase alphabets such that each character in a string doesn't appear more than twice. Examples: Input: N = 3, K = 2Output: 6Explanation:The possible strings are:"a", "b", "aa", "bb", "aba", "bab". Input: N = 4, K = 3Outpu
9 min read
Count pairs (p, q) such that p occurs in array at least q times and q occurs at least p times
Given an array arr[], the task is to count unordered pairs of positive integers (p, q) such that p occurs in the array at least q times and q occurs at least p times. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 1 (1, 1) is the only valid pair. Input: arr[] = {3, 3, 2, 2, 2} Output: 2 (2, 3) and (2, 2) are the only possible pairs. Approach: The
8 min read
Largest possible Subset from an Array such that no element is K times any other element in the Subset
Given an array arr[] consisting of N distinct integers and an integer K, the task is to find the maximum size of a subset possible such that no element in the subset is K times any other element of the subset(i.e. no such pair {n, m} should be present in the subset such that either m = n * K or n = m * K). Examples: Input: arr[] = {2, 8, 6, 5, 3},
7 min read
Minimize the maximum of Array by replacing any element with other element at most K times
Given an array arr[] of size N and an integer K, the task is to minimize the value of the maximum element of the array arr[] after replacing any element of the array with any other element of that array at most K times. Examples: Input: arr[] = {5, 3, 3, 2, 1}, K = 3Output: 2Explanation: Replace the elements at index 0, 1 and 2 with the value 1.The
8 min read
Count subarrays having each distinct element occurring at least twice
Given an array arr[] of size N, the task is to count the number of subarrays from the given array, such that each distinct element in these subarray occurs at least twice. Examples: Input: arr[] = {1, 1, 2, 2, 2}Output: 6Explanation: Subarrays having each element occurring at least twice are :{{1, 1}, {1, 1, 2, 2}, {1, 1, 2, 2, 2}, {2, 2}, {2, 2, 2
8 min read
Smallest occurring element in each subsequence
Given an array of N distinct integers. For each element the task is to find the count of subsequence from all the possible subsequence whose minimum element is the current element.Examples: Input: arr[] = {1, 2} Output: 2 1 Explanation: Subsequences are {1}, {2}, {1, 2}. The count of the smallest element in each subsequence is: 1 = 2, 2 = 1Input: a
6 min read
Maximum occurring element in a subarray range (Mode queries)
Given an array arr[] of N integers, and an array Q[] of M pairs, where a pair represents a query of the form {L, R}, the task is to find the maximum occurring element in the range [L, R] and its frequency for each query. If there are multiple elements with maximum frequency, then print the maximum element among them. Examples: Input: arr[] = {5, 7,
15 min read
Find an index of maximum occurring element with equal probability
Given an array of integers, find the most occurring element of the array and return any one of its indexes randomly with equal probability.Examples: Input: arr[] = [-1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5, 7, 8, 9] Output: Element with maximum frequency present at index 6 OR Element with maximum frequency present at Index 3 OR Element with maximum freq
8 min read
Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element
Given an array arr[] consisting of N integers, the task is to find the remaining array element after subtracting each element from its next adjacent element and removing the last array element repeatedly. Examples: Input: arr[] = {3, 4, 2, 1}Output: 4Explanation:Operation 1: The array arr[] modifies to {4 - 3, 2 - 4, 1 - 2} = {1, -2, -1}.Operation
8 min read
Find just strictly greater element from first array for each element in second array
Given two arrays A[] and B[] containing N elements, the task is to find, for every element in the array B[], the element which is just strictly greater than that element which is present in the array A[]. If no value is present, then print 'null'. Note: The value from the array A[] can only be used once. Examples: Input: A[] = {0, 1, 2, 3, 4}, B[]
10 min read
Build a DFA to accept a binary string containing "01" i times and "1" 2j times
Given a binary string str, the task is to build a DFA that accepts given binary string if it contains "01" i times and "1" 2j times, i.e., [Tex]L={(01)^i (1)^{2j} \text{ where }i\geq1\text{ and }j\geq1} [/Tex] Examples: Input: str = "011111" Output: Accepted Explanation: The string follows the language as: (01)1(1)2*2 Input: str = "01111" Output: N
9 min read
Article Tags :
Practice Tags :