Find the Largest Almost Missing Integer
ā Runtime tested ā the solution passes every example case. š Full written solution: https://interview-kit-fe.vercel.app/find-the-largest-almost-missing-integer š» Code on GitHub: https://github.com/timepasshub2539-hue/leetcode-python/tree/main/find-the-largest-almost-missing-integer Chapters: 0:00 The Problem 0:23 The 90 Percent Skip Trick 0:43 Sliding Window Setup 0:53 Almost Missing Definition 1:06 Brute-Force Approach 1:27 The Middle Element Trap 1:36 Only Edges Matter 2:18 Counting Frequencies Once 2:34 Finding Edge Positions 2:52 Checking A Candidate 3:06 Picking The Largest Winner 3:19 Full Python Solution 3:29 Dry Run Example 3:42 Time And Space Complexity 4:00 Common Mistake To Avoid 4:15 Recap 4:36 The Core Trick 4:49 Quick Quiz! 4:57 Quick Quiz! 5:02 Quick Quiz! 5:12 Round 2! 5:19 Round 2! 5:24 Round 2! 5:30 Proof Of Correctness 5:39 Runtime Benchmark We break down LeetCode 3471, Find the Largest Almost Missing Integer, and show why almost every element can be ignored without checking a single window. You'll see what 'almost missing' actually means, why the middle of the array is a trap that wastes time, and how counting occurrences once turns a brute-force scan into a fast edge-only check. Includes a full dry run on the real example, a complexity breakdown, the tempting mistake most people make, and a proof plus timing comparison against brute force. #leetcode #python #coding #dsa #softwareengineering Watch next: - The Problem: Find the Largest Almost Missing Integer #shorts: https://youtu.be/g827duoB4Is - 3471. Find the Largest Almost Missing Integer | LeetCode Daily Python Solution (3 windows, 1 answer): https://youtu.be/t_IZa2s2qGU - SQL Lesson 25: Find 1 Row in 1 Million in Just 20 Steps: https://youtu.be/6HKTw5GL0Ts
Introduction
Sliding window problems show up constantly in coding interviews because they test something more valuable than syntax: can you reason about coverage? Which elements get touched by how many windows, and why? Find the Largest Almost Missing Integer (LeetCode 3471) looks like a straightforward "check every window" problem at first glance, but it's really testing whether you notice a structural shortcut hiding in plain sight ā most of the array can be eliminated before you check a single value.
This is the kind of problem interviewers like because the brute force is easy to write and easy to justify, but it wastes an enormous amount of work on positions that were never going to matter. Learning to spot that waste, and to prove why it's safe to skip it, is a transferable skill you'll use in dozens of other sliding window and array problems.
Problem Overview
You're given an integer array nums and a window size k. Slide a window of exactly k consecutive elements across the array, one step at a time ā so you get a sequence of overlapping windows, each covering a different k-length stretch.
A value counts as "almost missing" if it appears in exactly one of these windows ā not zero, and not two or more. Among all almost missing values, return the largest one. If no value qualifies, return -1.
The key subtlety: this is about how many windows contain the value's position, not how many times the value appears in the array. Those are related but not identical, and mixing them up is the most common way to get this problem wrong.
Example
nums = [3, 9, 2, 1, 7], k = 3
The windows are:
| Window | Elements |
|---|---|
| 0 | [3, 9, 2] |
| 1 | [9, 2, 1] |
| 2 | [2, 1, 7] |
3(index 0) appears only in window 0 ā exactly one window.9(index 1) appears in windows 0 and 1 ā two windows, disqualified.2(index 2) appears in windows 0, 1, and 2 ā disqualified.1(index 3) appears in windows 1 and 2 ā disqualified.7(index 4) appears only in window 2 ā exactly one window.
Qualifying values: 3 and 7. The answer is 7, the larger of the two.
Intuition
Start by asking a simpler question: for a fixed window size k sliding across an array of length n, how many windows pass over a given index i?
Pick an index dead center in the array. Windows can start anywhere from a certain point before it to a certain point after it, and as long as the window still contains i, it counts. For a middle index, that range of valid starting positions is exactly k positions wide ā so a middle element gets covered by k different windows.
If k is anything more than 1, that's already more than one window. So no interior element can ever be almost missing, no matter what value it holds. You never need to check it.
Coverage only drops below k near the two edges. The first few indices get fewer windows sliding over them as you approach index 0, because there's no room for a window to start before the array does. The mirror image happens at the last few indices. Only index 0 and index n-1 are guaranteed to sit in exactly one window each ā everything else near the edges is still touched by more than one unless k happens to be very small relative to n.
There's one trap: this reasoning assumes k < n. If k == n, there's only one window ā the entire array ā so literally every element sits in exactly one window, even if the value repeats. It's tempting to reuse "does this value appear only once in the array" as the qualifying check, but that's a different question entirely. Consider nums = [5, 5], k = 2: there's one window, both 5s are inside it, and the correct answer is 5 ā not -1, even though 5 appears twice in the array.
Once you separate "how many windows cover this position" from "does this value repeat elsewhere," the rest is bookkeeping: build a frequency map of the array, identify the tiny set of guaranteed single-window positions, and check just those.
Brute Force Solution
Idea: For every distinct value in the array, count how many windows contain it, and keep it if the count is exactly 1.
Algorithm:
- Generate every window of size
k. - For each distinct value in the array, scan every window and count how many contain that value.
- Keep values with a count of exactly 1.
- Return the largest, or
-1.
Advantages: Obviously correct, easy to reason about, no edge case analysis required.
Disadvantages: Every value is checked against every window ā the work scales with both the number of elements and the number of windows, which is roughly O(n * (n - k)), effectively O(n²) for many inputs. It passes on small constraints but does a lot of unnecessary work.
Time Complexity: O(n²) in the general case. Space Complexity: O(n) for tracking window membership.
Optimal Solution
The optimal approach follows directly from the intuition above:
- Build a frequency map of the entire array in one pass ā a plain counter that answers "how many times does value
vappear anywhere innums?" in O(1). - Identify the edge positions ā the indices actually guaranteed to sit in exactly one window:
- If
k == n: there is only one window total, so every index qualifies as an edge position. - If
k == 1: every element is its own window, so again every index qualifies. - Otherwise: only
index 0andindex n-1are guaranteed single-window positions.
- If
- Check only those edge positions. For each one, look up its value's count in the frequency map. If the count is exactly 1 (the value doesn't repeat anywhere else in the array), it's genuinely almost missing.
- Track the maximum among qualifying values. If none qualify, return
-1.
The frequency check and the window-coverage check are answering two different questions, and you need both: the edge position guarantees the window-count is 1, and the frequency-count-of-1 guarantees the value itself doesn't sneak into a second occurrence elsewhere that could land in another window.
Python Code
from collections import Counter
from typing import List
def largest_almost_missing_integer(nums: List[int], k: int) -> int:
n = len(nums)
freq = Counter(nums)
# Determine which positions are guaranteed to sit in exactly one window.
if k == n or k == 1:
edge_indices = range(n)
else:
edge_indices = (0, n - 1)
best = -1
for i in edge_indices:
value = nums[i]
if freq[value] == 1:
best = max(best, value)
return best
Code Walkthrough
freq = Counter(nums)builds the full frequency map in a single O(n) pass ā this answers "does this value repeat anywhere in the array?" for any value in O(1).- The
if k == n or k == 1branch handles the two special cases where every position is a valid edge position: a single giant window, or every element being its own window. - The
elsebranch is the general case ā only0andn - 1are guaranteed to be covered by exactly one window. - The loop only ever runs over 2 elements (or all
nin the special cases), checking each candidate's frequency and keeping the largest qualifying value. bestdefaults to-1, which naturally becomes the answer if nothing survives the check.
Dry Run
nums = [3, 9, 2, 1, 7], k = 3
n = 5,k = 3ā neitherk == nnork == 1, so edge indices are(0, 4).freq = {3: 1, 9: 1, 2: 1, 1: 1, 7: 1}.- Index 0 ā value
3āfreq[3] == 1ā qualifies ābest = 3. - Index 4 ā value
7āfreq[7] == 1ā qualifies ābest = max(3, 7) = 7. - Return
7.
Matches the expected output from the example above.
Complexity Analysis
Time: O(n) ā one pass to build the frequency map, followed by a constant number of lookups (2 in the general case, n in the two special cases, which are themselves O(n) overall). No nested scanning of windows against values.
Space: O(n) for the frequency map, since in the worst case every value in the array is distinct.
This is correct because the frequency map is built once and reused for O(1) lookups, and the number of positions actually checked is bounded by a constant (or by n only in the special cases, which still keeps the whole algorithm linear).
Alternative Solutions
You could compute, for every index, exactly how many windows cover it using a formula (min(i, n - k, k - 1, n - i - 1) + 1), then filter to positions with a coverage count of 1. This generalizes the same idea but is unnecessary here ā since we already know analytically which positions can have coverage 1 (the two edges, or all positions in the two special cases), computing the general formula for every index is extra work for the same answer.
Edge Cases
- Empty array: Not a valid input per constraints, but defensively returns
-1since there are no edge indices to check. k == n: Every index is a valid edge position; duplicates inside that single window still count as qualifying (see the[5, 5]example).k == 1: Every element is its own window, so the answer is simply the largest value in the array.- All duplicate values: No value has
freq[value] == 1(unlessk == nork == 1), so the answer is-1. - Two-element array with
k == 1: Both elements qualify as their own windows; the larger one wins even if they're equal.
Common Mistakes
- Confusing "appears once in the array" with "appears in exactly one window." These overlap for the general case but diverge completely when
k == n. - Forgetting the
k == nspecial case, which causes correct-looking code to wrongly return-1on inputs like[5, 5]withk = 2. - Forgetting the
k == 1special case, where every index is technically an edge and the frequency check still matters. - Assuming positions near the start are automatically edge positions. Index 1 is not guaranteed to be in only one window ā only index 0 and index
n - 1are, unlesskis 1 orn. - Running the brute force window-by-window check on every value, which is correct but needlessly quadratic ā missing the coverage argument entirely.
Interview Questions
- Why can't a value in the middle of the array ever be almost missing when
1 < k < n? - How would the solution change if we wanted values appearing in at most one window instead of exactly one?
- Can you generalize the "edge position" formula for a version of this problem where the window doesn't have to be contiguous?
- How would you extend this to return all almost missing values, not just the largest?
Similar Problems
- Sliding Window Maximum (LeetCode 239) ā same window-sliding mechanic, different aggregate being tracked.
- Minimum Size Subarray Sum (LeetCode 209) ā another problem where reasoning about window boundaries avoids brute force.
- Contains Duplicate II (LeetCode 219) ā uses a similar "does this value repeat nearby" frequency-style check.
- Sliding Window Median (LeetCode 480) ā deeper sliding window problem where understanding what enters/exits the window each step is the whole challenge.
Key Takeaways
The core lesson generalizes far beyond this one problem: whenever you're sliding a fixed-size window across an array, coverage is not uniform ā it's high in the middle and thins out at the edges. Before writing any brute force scan, ask which positions actually have a chance of satisfying your condition, and check only those. Here, that insight took an O(n²) scan down to a single O(n) pass followed by two lookups.
Watch the Video
For the full walkthrough with a live dry run, timing comparison against brute force, and the mid-explanation quiz, watch the video here: {LINK}
About the Series
This breakdown is part of Fun with Learning Technology, a daily series covering LeetCode problems, algorithms, and practical software engineering topics ā built for developers who want to understand the why behind a solution, not just memorize the code. New videos drop daily.
Call To Action
If this explanation clicked for you, drop a like on the video and subscribe on YouTube ā new problems every day. For the deeper technical write-ups like this one delivered straight to your inbox, subscribe to the Substack. Comments are open ā tell me which problem you want broken down next.
The solution
from collections import Counter
class Solution:
def largestInteger(self, nums, k):
n = len(nums)
freq = Counter(nums)
edges = range(n) if k in (n, 1) else [0, n - 1]
best = -1
for i in edges:
v = nums[i]
if freq[v] == 1:
best = max(best, v)
return bestReady to try it yourself? Solve Twopointer problems with instant feedback in the practice sandbox.
Practice now ā


