> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Find Lucky Integer in an Array Python Solution

> Tested Python solution for LeetCode 1394 with 27 pytest cases. Generate a practice environment with lcpy.

LeetCode 1394, [Easy](/catalog/easy). Topics: [Array](/catalog/topics/array), [Hash Table](/catalog/topics/hash-table), [Counting](/catalog/topics/counting). [View on LeetCode](https://leetcode.com/problems/find-lucky-integer-in-an-array/description/).

Generate this problem as a practice environment: tested reference solution, 27 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 1394   # by problem number
lcpy gen -s find_lucky_integer_in_an_array   # by problem name
```

## Problem

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`.

### Examples

```
Input: arr = [2,2,3,4]
Output: 2
Explanation: The only lucky number in the array is 2 because frequency[2] == 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.
```

```
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

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/find_lucky_integer_in_an_array/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/find_lucky_integer_in_an_array/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(n)
    def find_lucky(self, arr: list[int]) -> int:
        counts: dict[int, int] = {}
        for value in arr:
            counts[value] = counts.get(value, 0) + 1
        result = -1
        for value, count in counts.items():
            if value == count:
                result = max(result, value)
        return result
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.