1394. Find Lucky Integer in an Array

Easy
O(n)
Time
O(n)
Space
70.1%
Acceptance

Problem Description

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.

🍀

Lucky Integer

An integer where frequency = value

Value: 3, Frequency: 3 → Lucky! ✨

Input Array

Step-by-Step Process

Analyzing...

Frequency Analysis

Result

-
Lucky Integer
Array Length: -
Unique Numbers: -
Lucky Numbers: -

Algorithm Explanation

1

Count Frequencies

Create a frequency map to count occurrences of each number

2

Find Lucky Numbers

Check each number where frequency equals the value

3

Return Maximum

Return the largest lucky number, or -1 if none exist

Time Complexity

O(n)

Single pass to count frequencies + single pass to find lucky numbers

Space Complexity

O(n)

HashMap to store frequency counts

JavaScript Implementation

function findLucky(arr) {
    // Count frequencies
    const freq = new Map();
    for (const num of arr) {
        freq.set(num, (freq.get(num) || 0) + 1);
    }
    
    // Find lucky numbers
    let maxLucky = -1;
    for (const [num, count] of freq) {
        if (num === count) {
            maxLucky = Math.max(maxLucky, num);
        }
    }
    
    return maxLucky;
}

Examples

Example 1

Simple

Input: [2,2,3,4]

Output: 2

Explanation: Only 2 appears 2 times

Example 2

Multiple

Input: [1,2,2,3,3,3]

Output: 3

Explanation: 1, 2, and 3 are lucky. Return max: 3

Example 3

No Lucky

Input: [2,2,2,3,3]

Output: -1

Explanation: No lucky numbers exist

Performance Metrics

0ms
Execution Time
0KB
Memory Usage
0
Operations

Hints

Hint 1

Count the frequency of each number in the array using a HashMap or frequency array.

Hint 2

A number is lucky if its frequency equals its value. Check this condition for each unique number.