Smallest Absent Positive Greater Than Average Problem
#3678
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3678.
You are given an integer array nums.
Return the smallest absent positive integer in nums such that it is strictly greater than the average of all elements in nums.
The average of an array is defined as the sum of all its elements divided by the number of elements.
Example 1:
Input: nums = [3,5]
Output: 6
Explanation:
- The average of nums is (3 + 5) / 2 = 8 / 2 = 4.
- The smallest absent positive integer greater than 4 is 6.
Example 2:
Input: nums = [-1,1,2]
Output: 3
Explanation:
- The average of nums is (-1 + 1 + 2) / 3 = 2 / 3 = 0.667.
- The smallest absent positive integer greater than 0.667 is 3.
Example 3:
Input: nums = [4,-1]
Output: 2
Explanation:
- The average of nums is (4 + (-1)) / 2 = 3 / 2 = 1.50.
- The smallest absent positive integer greater than 1.50 is 2.
Constraints:
1 <= nums.length <= 100-100 <= nums[i] <= 100
Solution
Approach: Hash Set
Put all elements of nums into a hash set. The smallest integer strictly greater than the average is floor(avg) + 1, and the answer must also be positive, so start at max(1, floor(avg) + 1). While the candidate is in the set, increase it by one. The first value not in the set is the answer.
Complexity: O(n) time and O(n) extra space, where n is the length of nums.
class Solution:
def smallestAbsent(self, nums: List[int]) -> int:
s = set(nums)
ans = max(1, sum(nums) // len(nums) + 1)
while ans in s:
ans += 1
return ans