Show problems as
Classic problem #1394EasyArrayHash TableCounting

Find Lucky Integer in an Array

Real-world version: The Largest Self-Matching Token
Tracked in this browser only
Read Find Lucky Integer in an Array on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A tray holds tokens whose face values are listed in tokens. A value is matched when the tray holds exactly that many tokens of it, so 3 is matched when exactly three tokens show 3.

Return the largest matched value, or -1 when the tray holds no matched value at all.

Examples

Example 1

Input
tokens = [2, 2, 2]
Output
-1

Three tokens show 2, which is one too many for 2 to be matched, and no other value appears at all.

Example 2

Input
tokens = [4, 4, 4, 4, 5, 5, 5, 5, 5]
Output
5

Four tokens show 4 and five show 5, so both values are matched and the larger is reported.

Example 3

Input
tokens = [1]
Output
1

A lone token showing 1 is matched, since 1 turns up exactly once.

Constraints

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

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def find_lucky(tokens: list[int]) -> int:
Java
public int findLucky(int[] tokens)