KatInterview

Locate Gap in Sorted Consecutive Sequence

Heaps, Sorting & SearchAuto-graded · 21 test cases
EasyAuto-gradedHeaps, Sorting & Searcharraysbinary-search

Last updated

Detect a missing entry in a sorted contiguous array of integers in logarithmic time using binary search.

Given an array a of distinct, strictly increasing integers, the elements are expected to form an uninterrupted consecutive sequence starting from a[0].

At most one element within the range of the sequence is missing from a.

Write a function that identifies and returns the missing integer. If all elements in a are strictly consecutive and no internal gap exists, return None.

Constraints

  • 0 <= len(a) <= 10^5
  • -10^9 <= a[i] <= 10^9
  • a is strictly increasing (a[i] < a[i+1] for all valid i).
  • Time complexity must be strictly $O(\log n)$ where $n = \text{len}(a)$.
  • Auxiliary space complexity must be $O(1)$.

Examples

Example 1

Input: find_missing_value([4, 5, 6, 8, 9])

Output: 7

Example 2

Input: find_missing_value([-3, -2, -1, 0, 1])

Output: None

Example 3

Input: find_missing_value([10, 11, 12, 13, 15])

Output: 14

Hints

Hint 1

Notice that if no numbers were missing, every index `i` would satisfy `a[i] == a[0] + i`.

Hint 2

When a number is missing, `a[i] == a[0] + i` holds for all elements before the gap, but fails for all elements after the gap.

Hint 3

Since the condition changes from True to False at most once, you can use binary search to locate the first index where `a[i] != a[0] + i`.