← Bytedance Interview Insights
This is basically LC 228 but asking for the gaps instead of the covered ranges.
Use a linear scan through the sorted array while maintaining a pointer for the current expected number, starting at 'lower'. For each element, if it's greater than the current pointer, record the missing range from pointer to element-1; then update the pointer to element+1. After the loop, if the pointer is ≤ upper, record the final missing range.
Pro tip: Clarify edge cases upfront (e.g., empty array, bounds outside array range) and handle integer overflow by using long or careful arithmetic when computing element+1. Also, explicitly state the time and space complexity (O(n) time, O(1) extra space excluding output).
Restate the problem to ensure clarity: given a sorted unique array, find all missing ranges between lower and upper. Identify edge cases: empty array, array values outside bounds, single-element gaps, and multi-element gaps.
Set a pointer 'prev' to lower (the start of the current missing range) and create an empty list for results. Iterate through each number in the array.
For each number 'num', if num > prev, then there is a missing range from prev to num-1. Add this range to the result (as a single number if prev == num-1, else as a pair). Then update prev to num+1.
After processing all elements, if prev <= upper, add the missing range from prev to upper to the result.
Return the list of missing ranges. Explain that the algorithm runs in O(n) time and O(1) extra space (excluding the output list).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.