Question:
How to find the element to occur K times using Java

Summary

In this case, the class Solution will be utilized. Its firstElementKTime method requires three parameters: n, k, and an integer array a. The method's objective is to locate the first element in array a that appears precisely k times.


Solution

class Solution

{

    public int firstElementKTime(int n, int k, int[] a) { 

        

        HashMap<Integer, Integer> map = new HashMap<>();

        

        for(int i = 0; i < n; i++){

            

            if(map.containsKey(a[i])){

                int occurance = map.get(a[i]) + 1;

                if(occurance == k) return a[i];

                

                map.put(a[i], occurance);

            }else{

                map.put(a[i], 1);

            }

        }

        

        return -1;

    } 

}


Explanation

  • HashMap Initialization: The function creates a HashMap with the name map, in which the values are integers that indicate the number of times each element appears, and the keys are integers that represent the elements of the array a.

  • A for loop is used in the method to iterate through the elements of the array a.

  • Counting Occurrences: The method determines if each element in the array, a[i], is already present in the map.


Answered by:> >mogilimanikanta5555

Credit:> >GeekforGeeks


Suggested blogs:

>How to detect whether the linked list has a loop using Java

>How to determine the number of valid groupings for a string using Java

>How to mock a constant value in Python?

>Creating a pivot table by 6 month interval rather than year

>How to Install mariaDB client efficiently inside docker?

>Can I call an API to find out the random seed in Python `hash()` function?

>How remove residual lines after merge two regions using Geopandas in python?


Submit
0 Answers