The task is to find the gaps between consecutive numbers in the array, with one added complication: the range [lower, upper] extends beyond the array itself. A correct solution has to account for gaps before the first element and after the last element, not only the gaps strictly between array elements.
Because the array is sorted and holds unique values, the missing numbers form contiguous blocks that sit between consecutive elements (and between the boundaries lower/upper and the nearest element). A missing block exists wherever two consecutive values differ by more than 1. That observation reduces the whole problem to a single linear scan.
0 <= nums.length <= 100 → n is small, so correctness and clean boundary handling matter more than asymptotic speed. A single linear pass already suffices.-10^9 <= lower <= upper <= 10^9 → Values span almost the full signed 32-bit range. The largest difference computed by either approach is at most about 2x10^9, which stays below the int32 limit of 2.147x10^9, so plain int is safe and no 64-bit type is required.nums is sorted and unique → No sorting or deduplication needed. The ordering alone drives the scan.Handle the three kinds of gaps in three separate steps. First, the gap between lower and the first element. Then the gaps between consecutive elements. Finally, the gap between the last element and upper. Each step gets its own block of code, which keeps the boundary logic explicit at the cost of some repetition.
nums is empty: the entire range [lower, upper] is missing.lower and nums[0]. If lower < nums[0], add the range [lower, nums[0] - 1].nums[i] and nums[i+1], check if nums[i+1] - nums[i] > 1. If so, add the range [nums[i] + 1, nums[i+1] - 1].nums[n-1] and upper. If nums[n-1] < upper, add the range [nums[n-1] + 1, upper].The three blocks above do the same gap check three times. The next approach folds them into one loop by adding virtual boundary elements at each end of the array.
Treat lower - 1 as a virtual element before the array and upper + 1 as a virtual element after it. With those two anchors in place, every gap check follows the same pattern. The separate code for "before the first element," "between elements," and "after the last element" collapses into one rule applied to consecutive entries of the extended sequence.
The empty-array case falls out of the same rule without special handling. When nums is empty, the loop runs once with prev = lower - 1 and curr = upper + 1. The check curr - prev > 1 becomes (upper + 1) - (lower - 1) > 1, which simplifies to upper >= lower. That always holds given the constraints, so the single range [lower, upper] is added, exactly the expected output for an empty array.
prev = lower - 1. This represents the element "just before" the range starts.nums[i], check if nums[i] - prev > 1. If so, add the range [prev + 1, nums[i] - 1] to the result.prev = nums[i].upper + 1 - prev > 1 (equivalently, prev < upper), add the range [prev + 1, upper].