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, nums contains start, start + 1, ..., start + len(nums) - 1, and your function must return None.
  • When a single value strictly between nums[0] and nums[-1] was skipped, nums spans start through start + 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^12
  • nums is strictly increasing (nums[i] < nums[i + 1] for all valid i).
  • Either nums has no gaps (len(nums) < 2 or nums[-1] - nums[0] == len(nums) - 1), or nums omits one integer (nums[-1] - nums[0] == len(nums)).
  • Required complexity: O(log n) time and O(1) extra memory.

Step-by-step walkthrough

  1. Understand the problem and why missing ends are ambiguous

    We receive an ascending array nums of unique integers drawn from a step-1 range starting at some integer start (negative, zero, or positive), with at most one interior value omitted:

    • Nothing omitted: nums equals [start, start + 1, ..., start + n - 1], and we return None. Notice in Example 3 ([-2, 0, 1, 2, 3]) that -1 itself can be the missing value, which is why returning None for "no missing element" avoids any sentinel collision.
    • One value omitted: nums covers start .. start + n with a single interior value skipped, and we return that skipped integer.

    Why can an identifiable gap only occur strictly between nums[0] and nums[-1]? Given [20, 21, 22], there is no way to distinguish whether 19 was dropped before the start, 23 was dropped after the end, or nothing was dropped at all—[20, 21, 22] is already a valid unbroken run, so the answer must be None.

  2. 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 None
    

    This 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 achieve O(log n) time, inspecting a single midpoint must rule out half of the remaining positions.

  3. Turn the array into a 0/1 shift pattern

    Let first_val = nums[0]. If no value has been skipped at or before index i, then slot i must hold first_val + i. Compare nums[i] with first_val + i on 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 = 15
    

    Look at the shift row (nums[i] - (first_val + i)):

    • Before the gap: every element sits in its unshifted slot (nums[i] == first_val + i, shift 0).
    • 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 where nums[i] != first_val + i. Once we find that boundary index left, the skipped integer is simply first_val + left—the value that belonged in that slot!

  4. Handle short or complete arrays in O(1) time

    Before starting binary search, two O(1) checks catch every None input immediately:

    1. If len(nums) < 2, no interior gap can exist between two numbers, so return None.
    2. In an unbroken step-1 array of length n, index n - 1 must equal first_val + (n - 1). Because nums holds 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 None
    

    Passing both guards establishes our search invariant before the loop begins: index 0 is unshifted (nums[0] == first_val) while index n - 1 is shifted (nums[n - 1] > expected_last_val), so the first shifted index must lie inside [1, n - 1].

  5. 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) // 2 and expected_mid_val = first_val + mid.
    • If nums[mid] == expected_mid_val, indices 0..mid have no gap, so advance left = mid + 1.
    • Otherwise, nums[mid] is already shifted, so the gap occurred at mid or to its left; keep mid in the window with right = mid (never mid - 1, because mid itself might be the first shifted index).

    Because floor division (left + right) // 2 satisfies mid < right whenever left < right, every pass either raises left to mid + 1 or lowers right to mid, guaranteeing termination at left == 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)!
    
  6. 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):

  1. Whole-array endpoint test: Without a gap, index 4 would hold 12 + 4 = 16. Since nums[4] is 17, a gap must lie inside [1, 4].
  2. Inspect midpoint mid = 2: nums[2] is 14, matching 12 + 2 = 14 (unshifted), so narrow [left, right] to [3, 4].
  3. Inspect midpoint mid = 3: nums[3] is 16, which differs from 12 + 3 = 15 (shifted!), so narrow [left, right] to [3, 3].
  4. Converge at left == right == 3: Slot 3 is the earliest shifted position, so the skipped integer is first_val + 3 = 12 + 3 = 15.

Complexity

  • Time: O(log n), where n = len(nums). Checking n < 2 and comparing nums[n - 1] with nums[0] + (n - 1) takes O(1) time (two list lookups). Whenever a gap exists, each iteration of while left < right reads one middle element and halves [left, right], taking at most ceil(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 duplicate nums.

Edge cases

  • Empty list [] or one-element list [42]: n < 2 returns None right away without touching invalid indices.
  • Unbroken run ([-6, -5, -4, -3]): nums[n - 1] == first_val + (n - 1) (-3 == -6 + 3) returns None in O(1) time before entering the binary search.
  • Two-element input: [1, 3] starts at left = 1, right = 1, skips the loop, and returns 1 + 1 = 2; [1, 2] exits via the O(1) endpoint check with None.
  • Gap right after index 0 or right before index n - 1: [-2, 0, 1, 2, 3] converges to left = 1 (returns -1), and [1, 2, 3, 5] converges to left = 3 (returns 4).
  • Missing 0 or -1: [-2, -1, 1, 2] returns 0 (callers must check result is None rather than if not result), and [-2, 0, 1, 2, 3] returns -1 (demonstrating why None is unambiguous compared to -1).
  • Large magnitudes (10^12): Only offsets from first_val matter, and Python ints do not overflow.

Common mistakes

  • Checking nums[mid] == mid instead of nums[mid] == nums[0] + mid: Assumes start == 0 and 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 - 1 when nums[mid] is shifted: Because mid itself may be the first shifted slot, mid - 1 discards the answer; always pair right = mid with while left < right.
  • Combining while left <= right with right = mid: Loops forever once left == right.
  • Returning nums[left] rather than first_val + left: nums[left] holds the element after the gap (16 in [12, 13, 14, 16, 17]), whereas the missing integer is first_val + left (15).
  • Calling sum(nums) or slicing nums[:mid]: Both perform O(n) work and violate the O(log n) requirement.

Alternative approaches

  • Adjacent-pair linear scan (O(n) time, O(1) space): Test nums[i] != nums[i - 1] + 1 for i from 1 to n - 1. Too slow for O(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] encloses missing_count = (nums[hi] - nums[lo]) - (hi - lo) skipped integers, computable in O(1) time. A recursive divide-and-conquer helper returns immediately whenever missing_count == 0, emits all integers from nums[lo] + 1 through nums[hi] - 1 when hi == lo + 1, and otherwise recurses on [lo, mid] and [mid, hi]. Across g gaps, this inspects only O(g log n) intervals (bounded by O(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 than nums[i] is missing_before(i) = nums[i] - nums[0] - i, which is monotonically non-decreasing with i. Binary search for the smallest index i satisfying missing_before(i) >= k: if none exists, the k-th missing value lies past the right end at nums[0] + (n - 1) + k; otherwise it equals nums[0] + i + k - 1 in O(log n) time and O(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 find lo = min(nums), hi = max(nums), and total = sum(nums): if hi - lo == n - 1 (or n < 2), return None; otherwise the unbroken range lo..hi has n + 1 integers, so (lo + hi) * (n + 1) // 2 - total (or combining lo..hi and nums with bitwise XOR, where x ^ x == 0 cancels matching pairs) recovers the missing integer in O(n) time and O(1) space.

Follow-up questions

Similar questions

More Arista interview questions

All 5 Arista questions →