#3678
Smallest Absent Positive Greater Than Average
EasyArrayHash TableHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Use a set to track existing numbers for quick lookup, then find the smallest absent positive integer greater than the average.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the average of nums.
- 2Step 2: Store all positive integers in a set for O(1) lookup.
- 3Step 3: Start from floor(avg) + 1 and find the first integer not in the set.
solution.py7 lines
1def smallestAbsent(nums):
2 avg = sum(nums) / len(nums)
3 num_set = set(nums)
4 x = int(avg) + 1
5 while x in num_set:
6 x += 1
7 return xℹ
Complexity note: The complexity is linear due to the single pass to create the set and another pass to find the absent integer.
- 1Using a set allows for faster lookups.
- 2The average helps to limit the search space for the absent integer.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.