Problem Description
Given an array of integers, a "lucky integer" is an integer whose frequency in the array is equal to its value. The task is to return the largest lucky integer. If no lucky integer exists, return -1.
Key Insights
- Use a hash table (or dictionary) to count the frequency of each integer.
- Compare each integer with its frequency and check if they match.
- Keep track of the maximum lucky integer found during the iteration.
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements in the array. Space Complexity: O(n), due to the usage of a hash table to store counts.
Solution
The solution involves iterating through the array and using a hash table to count how many times each number appears. After counting, iterate through the hash table to find all numbers where the number is equal to its count, which qualifies them as lucky integers. Finally, return the largest lucky integer, or -1 if none exist.