{x}
blog image

Find Lucky Integer in an Array

Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value.

Return the largest lucky integer in the array. If there is no lucky integer return -1.

 

Example 1:

Input: arr = [2,2,3,4]
Output: 2
Explanation: The only lucky number in the array is 2 because frequency[2] == 2.

Example 2:

Input: arr = [1,2,2,3,3,3]
Output: 3
Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them.

Example 3:

Input: arr = [2,2,2,3,3]
Output: -1
Explanation: There are no lucky numbers in the array.

 

Constraints:

  • 1 <= arr.length <= 500
  • 1 <= arr[i] <= 500

Solution Explanation: Find Lucky Integer in an Array

The problem asks to find the largest integer in an array whose frequency (number of occurrences) is equal to its value. This is solved efficiently using a frequency counting approach.

Approach:

  1. Frequency Counting: We first count the occurrences of each number in the input array arr. This can be done using a hash map (dictionary in Python) or an array if the range of numbers is known and relatively small (as it is in this problem, with numbers from 1 to 500).

  2. Finding Lucky Integers: We then iterate through the frequency counts. For each number x, we check if its frequency count[x] is equal to x. If it is, then x is a "lucky integer".

  3. Finding the Largest Lucky Integer: We keep track of the largest lucky integer encountered so far. Finally, we return this largest lucky integer or -1 if no lucky integer is found.

Time Complexity Analysis:

  • Frequency Counting: Iterating through the array arr once takes O(n) time, where n is the length of arr.
  • Finding Lucky Integers: Iterating through the frequency count (which has at most n entries) takes O(n) time in the worst case.
  • Overall: The dominant operation is the linear iteration, resulting in a time complexity of O(n).

Space Complexity Analysis:

The space complexity depends on the frequency counting data structure.

  • If we use a hash map, the space complexity is O(n) in the worst case (when all numbers are unique).
  • If we use an array (as shown in some solutions), the space complexity is O(k), where k is the maximum possible value in the input array (500 in this case). Since k is a constant, this is considered O(1) space complexity.

Code Examples (with explanations):

Python:

from collections import Counter
 
def findLucky(arr):
    """
    Finds the largest lucky integer in an array.
 
    Args:
        arr: The input array of integers.
 
    Returns:
        The largest lucky integer, or -1 if none exists.
    """
    count = Counter(arr)  # Efficiently counts the frequency of each number
    max_lucky = -1
    for num, freq in count.items(): #Iterates through the number and its frequency.
        if num == freq:
            max_lucky = max(max_lucky, num)  #Updates the max_lucky if the number is lucky.
    return max_lucky
 
 

Java:

import java.util.HashMap;
import java.util.Map;
 
class Solution {
    public int findLucky(int[] arr) {
        Map<Integer, Integer> count = new HashMap<>(); //Uses HashMap for frequency counting
        for (int num : arr) {
            count.put(num, count.getOrDefault(num, 0) + 1); //Increment frequency count for each number.
        }
        int maxLucky = -1;
        for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
            if (entry.getKey() == entry.getValue()) {
                maxLucky = Math.max(maxLucky, entry.getKey()); //Updates maxLucky if number is lucky.
            }
        }
        return maxLucky;
    }
}

C++:

#include <vector>
#include <map>
 
using namespace std;
 
class Solution {
public:
    int findLucky(vector<int>& arr) {
        map<int, int> count; //Uses map for frequency counting in c++.
        for (int num : arr) {
            count[num]++; 
        }
        int maxLucky = -1;
        for (auto const& [num, freq] : count) { //Iterates through the map in c++.
            if (num == freq) {
                maxLucky = max(maxLucky, num);
            }
        }
        return maxLucky;
    }
};

The other languages (Go, TypeScript, PHP) follow a similar logic, using appropriate data structures for frequency counting in their respective languages. The core algorithm remains the same, offering efficient O(n) time complexity and O(n) or O(1) space complexity.