LeetCode 1394 · Hashing

Find Lucky Integer in an Array, explained with a picture

A raffle number that matches its count.

Hashing
▶ Watch it step by step

The problem

A number is lucky if it appears exactly as many times as its value. Return the largest lucky number, or −1.

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

Picture it

Picture raffle tickets: count how many times each number was drawn, then look for numbers whose count equals the number itself, and keep the biggest.

Short version: the full lesson (brute force, complexity, edge cases and a quiz) is still being written. The animation is complete.

The key idea

Count with a dictionary, then check. O(n).

Python solution

def find_lucky(arr):
    count = Counter(arr)
    best = -1
    for x, c in count.items():
        if x == c:
            best = max(best, x)
    return best

LeetCode adds the imports for you. To run this on your own machine, put this at the top: from collections import Counter

In the interactive version each line lights up as the animation runs, and you can type your own input to see the algorithm handle it.