Problem 1394

Abstract / Summary

Find an integer in an array whose frequency equals its own value.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1394.py

class Solution:
    def findLucky(self, arr: List[int]) -> int:
        freq = defaultdict(int)
        for a in arr:
            freq[a] += 1

        for f in sorted(freq, reverse = True):
            if f == freq[f]:
                return f

        return -1
11 lines | 275 bytes | submitted November 9, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 69% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Counting
  • Hash Table
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method findLucky. The method receives a list of integers and returns the largest “lucky” integer, where a lucky integer is defined as a value that appears in the list exactly as many times as its own value. If no such integer exists, the method returns -1. The algorithm builds a frequency map, then scans the distinct values in descending order to locate the highest lucky number.

Key Steps

Building the frequency map

The first logical block creates a dictionary that counts how many times each integer appears in the input list. A defaultdict with an integer default value is used so that each new key starts at zero and can be incremented directly.

freq = defaultdict(int)
for a in arr:
    freq[a] += 1

This step ensures that the subsequent lookup of a value’s occurrence count is a constant-time operation.

Scanning values in descending order

After the frequencies are known, the method iterates over the distinct keys of the dictionary, sorted from largest to smallest. By processing the keys in reverse order, the algorithm guarantees that the first lucky number encountered is the maximum possible lucky number, allowing an immediate return without further checks.

for f in sorted(freq, reverse=True):
    if f == freq[f]:
        return f

The condition f == freq[f] directly tests the lucky property: the integer f must appear exactly f times.

Returning the sentinel value

If the loop completes without finding any lucky integer, the method falls back to returning -1, which signals the absence of a valid result.

return -1

Edge Cases Handled

When the input list is empty, the frequency map remains empty, the sorted iteration yields no elements, and the method correctly returns -1. If the list contains only numbers that never satisfy the lucky condition-such as all values being larger than their occurrence count or all being smaller-the same fallback path is taken. The algorithm also correctly handles cases where multiple numbers satisfy the lucky condition; because the keys are examined from highest to lowest, the largest lucky number is returned. Duplicate values are naturally aggregated in the frequency map, so the count reflects the true number of occurrences regardless of how many times a particular integer appears.

Performance Optimizations

The use of defaultdict(int) eliminates the need for explicit existence checks before incrementing a count, reducing overhead in the frequency-building phase. Sorting the distinct keys in descending order rather than scanning the entire list a second time focuses work on a much smaller set-the number of unique values-thereby minimizing the amount of data processed in the second phase. Additionally, the early return upon finding the first lucky number prevents unnecessary iteration over the remaining keys, which can be significant when the list contains many distinct values but the largest lucky number appears early in the sorted order. These choices collectively keep the runtime efficient for typical input sizes.

written by openai gpt

ELI5 - Simplified Explanation

Imagine having a big bag of colored building blocks. Some colors appear once, some appear twice, and others might appear five times. The goal of this code is to find a very special number.

First, the code makes a tiny notebook to keep track of every block. It looks at each block in the bag one by one. Every time a block shows up, the code writes its color and a little tick mark in the notebook. By the end, the notebook knows exactly how many blocks of each kind are inside.

Next, the code flips through the notebook starting with the biggest numbers first. It looks at each color and asks a simple question. It checks if the number written on the block is the exact same as the count of how many times that block appeared. If the number on the block is the same as the number of times it was found in the bag, the code has found the lucky winner. If it finishes looking through everything and finds nothing that matches, it simply gives up and decides there are no lucky numbers today.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.74 | σ = 1.35

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go PHP Rust TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fsq C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, PHP, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
varunu28 Java
29 links | 16 authors | 10 languages

Videos

10 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

11 solutions   November 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality