#1394

Find Lucky Integer in an Array

Easy
ArrayHash TableCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a hash map to count the occurrences of each number in one pass, making it more efficient. This allows us to check for lucky integers in a single traversal.

⚙️

Algorithm

2 steps
  1. 1Step 1: Create a frequency map to count occurrences of each number in the array.
  2. 2Step 2: Iterate through the frequency map to find the largest lucky integer where the key equals its value.
solution.py8 lines
1def findLucky(arr):
2    from collections import Counter
3    freq = Counter(arr)
4    max_lucky = -1
5    for num, count in freq.items():
6        if num == count:
7            max_lucky = max(max_lucky, num)
8    return max_lucky

Complexity note: The time complexity is O(n) because we traverse the array once to build the frequency map and then iterate through the map, which is much faster than the brute force approach. The space complexity is O(n) due to the storage of the frequency map.

  • 1Using a frequency map allows for efficient counting of occurrences.
  • 2The largest lucky integer is found by comparing keys and their values in the frequency map.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.