πΉ Problem: 1394 Find Lucky Integer in an Array
Difficulty: #Easy
Tags: #Array, #HashTable, #Counter
π Problem Summary
Youβre given an array of integers. A lucky integer is an integer whose value is equal to its frequency in the array.
You need to find the largest lucky integer, or return -1 if none exist.
π§ My Thought Process
-
Brute Force Idea:
- Count frequency of each element manually using nested loops.
- Check if the elementβs value equals its frequency.
- Time complexity would be horrible β O(nΒ²). Clearly not great.
-
Optimized Strategy:
- Use a
Counter
fromcollections
to get frequency in O(n). - Then, iterate over the frequency map in descending order of the key.
- Return the first value where the key matches its frequency.
- Why descending order? Because we need the largest such lucky integer.
- Use a
Algorithm Used:
[[Counter]]
βοΈ Code Implementation (Python)
from collections import Counter
class Solution:
def findLucky(self, arr: List[int]) -> int:
c = Counter(arr)
for k in sorted(c.keys(), reverse=True):
if k == c[k]:
return k
return -1
β±οΈ Time & Space Complexity
- Time: O(n log n) β for sorting the keys
- Space: O(n) β to store frequencies in the counter
π§© Key Takeaways
- β
Learned that combining
Counter
with sorted key traversal solves many frequency-based problems efficiently. - π‘ Sorting in reverse helped instantly grab the maximum valid lucky number.
- π This is a great pattern: frequency check + reverse sort for max/min valid value extraction.
π Reflection (Self-Check)
- [x] Could I solve this without help?
- [x] Did I write code from scratch?
- [x] Did I understand why it works?
- [x] Will I be able to recall this in a week?
Honestly, this was one of those satisfying ones where everything just clicked.
π Progress Tracker
Metric | Value |
---|---|
Day | 38 |
Total Problems Solved | 374 |
Confidence Today | π |
Top comments (0)