Find Lucky Integer in an Array — LeetCode 1394 Python Solution
- Problem
- #1394
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- arr = [2,2,3,4]
- Output
- 2
- Explanation
- The only lucky number in the array is 2 because frequency[2] == 2.
Python solution
class Solution:
def findLucky(self, arr: List[int]) -> int:
cnt = Counter(arr)
return max((x for x, v in cnt.items() if x == v), default=-1)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the length of the \textit{arr} auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1394. Find Lucky Integer in an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1394. Find Lucky Integer in an Array?
- LeetCode 1394. Find Lucky Integer in an Array is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1394. Find Lucky Integer in an Array?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1394. Find Lucky Integer in an Array?
- The Python solution on this page uses O(n), where n is the length of the \textit{arr} auxiliary space.
- What topics does LeetCode 1394. Find Lucky Integer in an Array cover?
- LeetCode 1394. Find Lucky Integer in an Array is tagged Array, Hash Table and Counting on LeetCode.