Find the Largest Almost Missing Integer Problem
#3471
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 3471.
You are given an integer array nums and an integer k.
An integer x is almost missing from nums if x appears in exactly one subarray of size k within nums.
Return the largest almost missing integer from nums. If no such integer exists, return -1.
A subarray is a contiguous sequence of elements within an array.
Example 1:
Input: nums = [3,9,2,1,7], k = 3
Output: 7
Explanation:
- 1 appears in 2 subarrays of size 3: [9, 2, 1] and [2, 1, 7].
- 2 appears in 3 subarrays of size 3: [3, 9, 2], [9, 2, 1], [2, 1, 7].
- 3 appears in 1 subarray of size 3: [3, 9, 2].
- 7 appears in 1 subarray of size 3: [2, 1, 7].
- 9 appears in 2 subarrays of size 3: [3, 9, 2], and [9, 2, 1].
We return 7 since it is the largest integer that appears in exactly one subarray of size k.
Example 2:
Input: nums = [3,9,7,2,1,7], k = 4
Output: 3
Explanation:
- 1 appears in 2 subarrays of size 4: [9, 7, 2, 1], [7, 2, 1, 7].
- 2 appears in 3 subarrays of size 4: [3, 9, 7, 2], [9, 7, 2, 1], [7, 2, 1, 7].
- 3 appears in 1 subarray of size 4: [3, 9, 7, 2].
- 7 appears in 3 subarrays of size 4: [3, 9, 7, 2], [9, 7, 2, 1], [7, 2, 1, 7].
- 9 appears in 2 subarrays of size 4: [3, 9, 7, 2], [9, 7, 2, 1].
We return 3 since it is the largest and only integer that appears in exactly one subarray of size k.
Example 3:
Input: nums = [0,0], k = 1
Output: -1
Explanation:
There is no integer that appears in only one subarray of size 1.
Constraints:
1 <= nums.length <= 500 <= nums[i] <= 501 <= k <= nums.length
Solution
Approach: Case Analysis
- If
k = 1, every element is a subarray of its own, so an integer is almost missing when it occurs exactly once. Return the largest such value. - If
k = n, the only subarray is the whole array, so every element is in it: return the maximum. - If
1 < k < n, onlynums[0](in just the first subarray) andnums[n-1](in just the last) can be in exactly one subarray, and only if they do not occur anywhere else in the array. Check both and return the larger one that qualifies.
Return -1 if nothing qualifies.
Complexity: O(n) time, O(n) space.
from collections import Counter
class Solution:
def largestInteger(self, nums: List[int], k: int) -> int:
def f(k: int) -> int:
for i, x in enumerate(nums):
if i != k and x == nums[k]:
return -1
return nums[k]
if k == 1:
cnt = Counter(nums)
return max((x for x, v in cnt.items() if v == 1), default=-1)
if k == len(nums):
return max(nums)
return max(f(0), f(len(nums) - 1))