Missing Integer in a Sorted Step-One Sequence
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You are given an ascending array nums of unique integers. The elements come from an integer range that steps upward by 1 starting at an unspecified integer start (which may be negative, zero, or positive).
At most one interior value from that step-1 run has been omitted:
- When every value is present,
numscontainsstart, start + 1, ..., start + len(nums) - 1, and your function must returnNone. - When a single value strictly between
nums[0]andnums[-1]was skipped,numsspansstartthroughstart + len(nums)without that value, and your function must return the skipped integer.
Implement find_missing_value(nums: List[int]) -> Optional[int] so that it runs in O(log n) time using O(1) auxiliary space, where n = len(nums).
Examples
Example 1
Input: nums = [12, 13, 14, 16, 17]
Output: 15
Walk-through: Starting at 12, stepping by 1 produces 12, 13, 14, 15, 16, 17. Because nums jumps directly from 14 to 16, the omitted integer is 15.
Example 2
Input: nums = [-6, -5, -4, -3]
Output: None
Walk-through: Every adjacent pair differs by 1 across the entire run from -6 to -3, so no interior value is missing and the result is None.
Example 3
Input: nums = [-2, 0, 1, 2, 3]
Output: -1
Walk-through: The sequence begins at -2 and skips -1 before continuing consecutively through 0, 1, 2, 3, so -1 is returned.
Constraints
0 <= len(nums) <= 10^5-10^12 <= nums[i] <= 10^12numsis strictly increasing (nums[i] < nums[i + 1]for all validi).- Either
numshas no gaps (len(nums) < 2ornums[-1] - nums[0] == len(nums) - 1), ornumsomits one integer (nums[-1] - nums[0] == len(nums)). - Required complexity:
O(log n)time andO(1)extra memory.
Step-by-step walkthrough
Understand the problem and why missing ends are ambiguous
We receive an ascending array
numsof unique integers drawn from a step-1range starting at some integerstart(negative, zero, or positive), with at most one interior value omitted:- Nothing omitted:
numsequals[start, start + 1, ..., start + n - 1], and we returnNone. Notice in Example 3 ([-2, 0, 1, 2, 3]) that-1itself can be the missing value, which is why returningNonefor "no missing element" avoids any sentinel collision. - One value omitted:
numscoversstart .. start + nwith a single interior value skipped, and we return that skipped integer.
Why can an identifiable gap only occur strictly between
nums[0]andnums[-1]? Given[20, 21, 22], there is no way to distinguish whether19was dropped before the start,23was dropped after the end, or nothing was dropped at all—[20, 21, 22]is already a valid unbroken run, so the answer must beNone.- Nothing omitted:
Start with the O(n) linear scan and see why it is too slow
A direct scan walks from left to right and checks whether each element equals its predecessor plus
1:def find_missing_linear(nums: List[int]) -> Optional[int]: for i in range(1, len(nums)): if nums[i] != nums[i - 1] + 1: return nums[i - 1] + 1 return NoneThis uses
O(1)extra memory—and makes a handy oracle for randomized tests—but when the gap sits near the right end or when no value is missing, it inspects every element (O(n)time). To achieveO(log n)time, inspecting a single midpoint must rule out half of the remaining positions.Turn the array into a 0/1 shift pattern
Let
first_val = nums[0]. If no value has been skipped at or before indexi, then slotimust holdfirst_val + i. Comparenums[i]withfirst_val + ion Example 1 (nums = [12, 13, 14, 16, 17]):index i : 0 1 2 3 4 nums[i] : 12 13 14 16 17 expected (12 + i) : 12 13 14 15 16 shift : 0 0 0 +1 +1 ^ first shifted index = 3 -> missing value is 12 + 3 = 15Look at the
shiftrow (nums[i] - (first_val + i)):- Before the gap: every element sits in its unshifted slot (
nums[i] == first_val + i, shift0). - After the gap: every element is pushed up by
1(nums[i] == first_val + i + 1, shift+1).
Because all
0s precede all+1s, we can binary search for the first index wherenums[i] != first_val + i. Once we find that boundary indexleft, the skipped integer is simplyfirst_val + left—the value that belonged in that slot!- Before the gap: every element sits in its unshifted slot (
Handle short or complete arrays in O(1) time
Before starting binary search, two
O(1)checks catch everyNoneinput immediately:- If
len(nums) < 2, no interior gap can exist between two numbers, so returnNone. - In an unbroken step-
1array of lengthn, indexn - 1must equalfirst_val + (n - 1). Becausenumsholds strictly increasing integers,nums[n - 1] == first_val + (n - 1)is true if and only if zero values are missing!
n = len(nums) # Fewer than 2 elements cannot contain an interior gap between two numbers. if n < 2: return None first_val = nums[0] expected_last_val = first_val + (n - 1) # Phase 1: Quick O(1) check — if the last element equals first_val + (n - 1), # every slot from index 0 to n - 1 holds its exact consecutive integer. if nums[n - 1] == expected_last_val: return NonePassing both guards establishes our search invariant before the loop begins: index
0is unshifted (nums[0] == first_val) while indexn - 1is shifted (nums[n - 1] > expected_last_val), so the first shifted index must lie inside[1, n - 1].- If
Binary search for the first shifted index and trace Examples 1 and 2
Maintain
[left, right]initialized to[1, n - 1]so it always brackets the first shifted index:- Compute
mid = (left + right) // 2andexpected_mid_val = first_val + mid. - If
nums[mid] == expected_mid_val, indices0..midhave no gap, so advanceleft = mid + 1. - Otherwise,
nums[mid]is already shifted, so the gap occurred atmidor to its left; keepmidin the window withright = mid(nevermid - 1, becausemiditself might be the first shifted index).
Because floor division
(left + right) // 2satisfiesmid < rightwheneverleft < right, every pass either raiseslefttomid + 1or lowersrighttomid, guaranteeing termination atleft == right.Trace on Example 1: nums = [12, 13, 14, 16, 17] (n = 5, first_val = 12) End check: nums[4] = 17 != 12 + 4 (16) -> a gap exists! Pass 1: left = 1, right = 4 -> mid = (1 + 4) // 2 = 2 nums[2] = 14, expected = 12 + 2 = 14 (match -> move left = 3) Pass 2: left = 3, right = 4 -> mid = (3 + 4) // 2 = 3 nums[3] = 16, expected = 12 + 3 = 15 (shifted -> move right = 3) Stop: left == right == 3 -> return first_val + left = 12 + 3 = 15 Trace on Example 2: nums = [-6, -5, -4, -3] (n = 4, first_val = -6) End check: nums[3] = -3 == -6 + 3 (-3) -> return None immediately in O(1)!- Compute
Complete solution
Here is the full
O(log n)time,O(1)space implementation:from typing import Any, Dict, List, Optional, Set, Tuple def find_missing_value(nums: List[int]) -> Optional[int]: n = len(nums) # Fewer than 2 elements cannot contain an interior gap between two numbers. if n < 2: return None first_val = nums[0] expected_last_val = first_val + (n - 1) # Phase 1: Quick O(1) check — if the last element equals first_val + (n - 1), # every slot from index 0 to n - 1 holds its exact consecutive integer. if nums[n - 1] == expected_last_val: return None # Phase 2: Binary search for the FIRST index i where nums[i] != first_val + i. # Invariant: index 0 is unshifted, and index n - 1 is shifted up by 1, # so the first shifted index is guaranteed to lie inside [left, right]. left = 1 right = n - 1 while left < right: mid = (left + right) // 2 expected_mid_val = first_val + mid if nums[mid] == expected_mid_val: # Everything from index 0 through mid is consecutive with no gap, # so the first shifted index must lie strictly to the right of mid. left = mid + 1 else: # nums[mid] is already shifted up by 1, so the gap occurred at mid # or earlier; keep mid as a candidate using right = mid. right = mid # When left == right, left is the first shifted index, and first_val + left # is the exact consecutive number that belonged in that slot. return first_val + left✅ Submit now — all tests should pass.
Intuition & how it works
Imagine numbered lockers along a hallway starting at first_val (say 12, 13, 14, ...), where at most one locker number was skipped during installation. Every locker before the skipped number has label first_val + i at zero-based position i, while every locker from the gap onward has label first_val + i + 1—shifted ahead by 1. Because "is locker i shifted ahead of first_val + i?" forms a monotonic predicate (a yes/no test that stays False up to a cutoff and True everywhere after), binary search (repeatedly halving a sorted index interval by checking its midpoint) locates the exact transition index in logarithmic time.
A brute-force scan checking nums[i] != nums[i - 1] + 1 from left to right—or summing all elements and subtracting from an arithmetic series—has to inspect up to all n values when the gap sits near the tail or when nothing is missing. That takes O(n) time rather than O(log n).
Walk through Example 1, nums = [12, 13, 14, 16, 17] (n = 5, first_val = 12):
- Whole-array endpoint test: Without a gap, index
4would hold12 + 4 = 16. Sincenums[4]is17, a gap must lie inside[1, 4]. - Inspect midpoint
mid = 2:nums[2]is14, matching12 + 2 = 14(unshifted), so narrow[left, right]to[3, 4]. - Inspect midpoint
mid = 3:nums[3]is16, which differs from12 + 3 = 15(shifted!), so narrow[left, right]to[3, 3]. - Converge at
left == right == 3: Slot3is the earliest shifted position, so the skipped integer isfirst_val + 3 = 12 + 3 = 15.
Complexity
- Time:
O(log n), wheren = len(nums). Checkingn < 2and comparingnums[n - 1]withnums[0] + (n - 1)takesO(1)time (two list lookups). Whenever a gap exists, each iteration ofwhile left < rightreads one middle element and halves[left, right], taking at mostceil(log2(n))steps. - Space:
O(1)auxiliary space, since we only keep a fixed set of integer variables (n,first_val,left,right,mid) and never slice or duplicatenums.
Edge cases
- Empty list
[]or one-element list[42]:n < 2returnsNoneright away without touching invalid indices. - Unbroken run (
[-6, -5, -4, -3]):nums[n - 1] == first_val + (n - 1)(-3 == -6 + 3) returnsNoneinO(1)time before entering the binary search. - Two-element input:
[1, 3]starts atleft = 1, right = 1, skips the loop, and returns1 + 1 = 2;[1, 2]exits via theO(1)endpoint check withNone. - Gap right after index
0or right before indexn - 1:[-2, 0, 1, 2, 3]converges toleft = 1(returns-1), and[1, 2, 3, 5]converges toleft = 3(returns4). - Missing
0or-1:[-2, -1, 1, 2]returns0(callers must checkresult is Nonerather thanif not result), and[-2, 0, 1, 2, 3]returns-1(demonstrating whyNoneis unambiguous compared to-1). - Large magnitudes (
10^12): Only offsets fromfirst_valmatter, and Python ints do not overflow.
Common mistakes
- Checking
nums[mid] == midinstead ofnums[mid] == nums[0] + mid: Assumesstart == 0and breaks on offset inputs such as[12, 13, 14, 16, 17]. - Omitting the
nums[n - 1] == first_val + (n - 1)guard: Without confirming that at least one shifted element exists, the binary search loop invariant (a property preserved across every iteration—here, that[left, right]contains a shifted index) fails on gap-free runs like[-6, -5, -4, -3]and falsely reports a missing value. - Setting
right = mid - 1whennums[mid]is shifted: Becausemiditself may be the first shifted slot,mid - 1discards the answer; always pairright = midwithwhile left < right. - Combining
while left <= rightwithright = mid: Loops forever onceleft == right. - Returning
nums[left]rather thanfirst_val + left:nums[left]holds the element after the gap (16in[12, 13, 14, 16, 17]), whereas the missing integer isfirst_val + left(15). - Calling
sum(nums)or slicingnums[:mid]: Both performO(n)work and violate theO(log n)requirement.
Alternative approaches
- Adjacent-pair linear scan (
O(n)time,O(1)space): Testnums[i] != nums[i - 1] + 1forifrom1ton - 1. Too slow forO(log n), though ideal as a test oracle. - Series sum or bitwise XOR (
O(n)time,O(1)space): Works even when the numbers arrive unsorted—see the follow-ups below.
Follow-up questions
- How would you adapt the algorithm if several integers could be missing and you needed to report all of them? Any subarray
nums[lo..hi]enclosesmissing_count = (nums[hi] - nums[lo]) - (hi - lo)skipped integers, computable inO(1)time. A recursive divide-and-conquer helper returns immediately whenevermissing_count == 0, emits all integers fromnums[lo] + 1throughnums[hi] - 1whenhi == lo + 1, and otherwise recurses on[lo, mid]and[mid, hi]. Acrossggaps, this inspects onlyO(g log n)intervals (bounded byO(n)) plus the number of output values. - How could you find the k-th missing integer after nums[0] in O(log n) time? At index
i, the number of omitted integers strictly smaller thannums[i]ismissing_before(i) = nums[i] - nums[0] - i, which is monotonically non-decreasing withi. Binary search for the smallest indexisatisfyingmissing_before(i) >= k: if none exists, thek-th missing value lies past the right end atnums[0] + (n - 1) + k; otherwise it equalsnums[0] + i + k - 1inO(log n)time andO(1)space. - What changes if the input array is unsorted? Without sorted order, every element must be read in the worst case (
O(n)lower bound), because changing the last unread value changes the answer. Scan once to findlo = min(nums),hi = max(nums), andtotal = sum(nums): ifhi - lo == n - 1(orn < 2), returnNone; otherwise the unbroken rangelo..hihasn + 1integers, so(lo + hi) * (n + 1) // 2 - total(or combininglo..hiandnumswith bitwise XOR, wherex ^ x == 0cancels matching pairs) recovers the missing integer inO(n)time andO(1)space.
Follow-up questions
- How would you adapt the algorithm if several integers could be missing and you needed to report all of them?
- How could you find the k-th missing integer after nums[0] in O(log n) time?
- What changes if the input array is unsorted?
Similar questions
- Delete Matching Nodes from a Singly Linked List
- Palindrome Verification and Skipped-Number Search
- Pointer Indirection, Format Specifiers, and Process Segments in C
- Raw-Storage Generic C++ Stack and Lifetime Semantics
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger