Skip to main content
Back to problems
Leetcode
Easy
Arrays
Hash Maps
Find Lucky Integer In An Array

Find the largest integer whose value is equal to its frequency in the array.

Acceptance 50%
Problem Statement

Given an integer array, find the largest lucky integer.

A number is called lucky if its value is exactly equal to how many times it appears in the array.

Return the largest lucky integer in the array. If no lucky integer exists, return -1.

You should solve this by examining the array values and their frequencies.

Input Format

  • An integer array arr.
  • Each element is an integer.

Output Format

Return the largest integer x such that x appears exactly x times in arr, or -1 if no such integer exists.

Constraints

  • 1 <= arr.length <= 500
  • 1 <= arr[i] <= 500
Examples
Sample cases returned by the problem API.

Example 1

Input

arr = [2,2,3,4]

Output

2

Explanation

2 appears exactly 2 times, so it is lucky. 3 appears once and 4 appears once, so they are not lucky.

Example 2

Input

arr = [1,2,2,3,3,3]

Output

3

Explanation

1 appears once, 2 appears twice, and 3 appears three times. The largest lucky integer is 3.

Show 1 more example

Example 3

Input

arr = [2,2,2,3,3]

Output

-1

Explanation

2 appears 3 times and 3 appears 2 times, so no value equals its frequency.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.