Find the Largest Almost Missing Integer - Problem
Find the Largest Almost Missing Integer

You are given an integer array nums and an integer k. Your task is to find the largest almost missing integer from the array.

An integer x is considered almost missing if it appears in exactly one subarray of size k within nums. In other words, when you slide a window of size k across the array, the integer x should appear in only one of these windows.

Goal: Return the largest such integer. If no almost missing integer exists, return -1.

Example: For nums = [1, 2, 3, 2, 4] and k = 3, the subarrays are [1,2,3], [2,3,2], and [3,2,4]. The number 4 appears in exactly one subarray, making it almost missing.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, 2, 3, 2, 4], k = 3
โ€บ Output: 4
๐Ÿ’ก Note: Subarrays of size 3 are: [1,2,3], [2,3,2], [3,2,4]. Number 1 appears in 1 subarray, number 4 appears in 1 subarray. The largest almost missing integer is 4.
example_2.py โ€” No Almost Missing
$ Input: nums = [1, 1, 1, 1], k = 2
โ€บ Output: -1
๐Ÿ’ก Note: Subarrays of size 2 are: [1,1], [1,1], [1,1]. Number 1 appears in all 3 subarrays, so there are no almost missing integers.
example_3.py โ€” Multiple Almost Missing
$ Input: nums = [5, 1, 2, 3, 4], k = 2
โ€บ Output: 5
๐Ÿ’ก Note: Subarrays of size 2 are: [5,1], [1,2], [2,3], [3,4]. Numbers 5 and 4 each appear in exactly one subarray. The largest is 5.

Constraints

  • 1 โ‰ค nums.length โ‰ค 104
  • 1 โ‰ค k โ‰ค nums.length
  • -104 โ‰ค nums[i] โ‰ค 104
  • Numbers can be negative

Visualization

Tap to expand
Sliding Window Frequency CountingArray: [1, 2, 3, 2, 4] with k = 312324Window 1: [1,2,3]Window 2: [2,3,2]Window 3: [3,2,4]Frequency Count:โ€ข Number 1: appears in 1 window โ†’ count = 1โ€ข Number 2: appears in 2 windows โ†’ count = 2โ€ข Number 3: appears in 2 windows โ†’ count = 2โ€ข Number 4: appears in 1 window โ†’ count = 1Max(1, 4) = 4
Understanding the Visualization
1
Position Window
Place a window of size k at the beginning of the array
2
Count Unique Numbers
For current window, add each unique number to frequency map
3
Slide Window
Move window one position right and repeat counting
4
Find Maximum
Among numbers with frequency = 1, return the largest
Key Takeaway
๐ŸŽฏ Key Insight: By using a sliding window and frequency counting, we can efficiently identify numbers that appear in exactly one subarray, then simply return the maximum among them.
Asked in
Google 23 Amazon 18 Meta 12 Microsoft 8
28.5K Views
Medium Frequency
~15 min Avg. Time
1.3K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen