-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFirst element to occur k times
53 lines (40 loc) · 1.25 KB
/
First element to occur k times
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package gfg;
//First element to occur k times
import java.util.*;
import java.io.*;
import java.lang.*;
public class GfG {
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
while(t-->0){
String inputLine[] = br.readLine().trim().split(" ");
int n = Integer.parseInt(inputLine[0]);
int k = Integer.parseInt(inputLine[1]);
int[] arr = new int[n];
inputLine = br.readLine().trim().split(" ");
for(int i=0; i<n; i++)
arr[i] = Integer.parseInt(inputLine[i]);
Solution obj = new Solution();
System.out.println(obj.firstElementKTime(n, k, arr));
}
}
}
class Solution
{
public int firstElementKTime(int n, int k, int[] a) {
Map<Integer, Integer> hash = new HashMap<>();
for(int i = 0; i < n; i++) {
if(hash.get(a[i]) == null) {
hash.put(a[i], 1);
}
else {
hash.put(a[i], hash.get(a[i]) + 1);
}
if(hash.get(a[i]) == k) {
return a[i];
}
}
return -1;
}
}