![]() |
VOOZH | about |
Given an array arr[] and an integer k, return the first element that appears at least k times; if none exists, return -1.
Examples:
Input: arr[] = [1, 7, 4, 3, 4, 8, 7], k = 2
Output: 4
Explanation: Both 7 and 4 occur 2 times. But 4 is first that occurs twice. At the index = 4, is the first element.Input: arr[] = [3, 1, 3, 4, 5, 1, 3, 3, 5, 4], k = 3
Output: 3
Explanation: Here, 3 is the only number that appeared atleast 3 times in the array.Input: arr[] = [10, 8, 2], k = 10
Output: -1
Explanation: Here no element is returning atleast 10 number of times, so -1.
Table of Content
To find the first element that occurs
ktimes, iterate through the array fromi = 0ton-1and count how many timesarr[i]has appeared in the range[0, i]using another loop. As soon as the count of any element becomes equal tok, return that element immediately since it is the first to reachkoccurrences. If no element reacheskoccurrences, return-1.
4
Traverse the array from
i = 0ton-1while maintaining a hash map to store the frequency of elements. As soon as its frequency of an element becomes equal tok, return that element immediately since it is the first to reachkoccurrences. If no element reacheskoccurrences, return-1.
4
Similar Problems: