
Problem Statement
In this task, you are provided with a specific range defined by two integers, lower
and upper
, and a unique sorted integer array nums
where each integer falls within the inclusive range between lower
and upper
. Your objective is to identify numbers that are missing from this range; these are numbers that lie between lower
and upper
but are not present in the nums
array. The goal is to return a concise list of ranges. Each range in this list should encapsulate a series of consecutive missing numbers. Additionally, the entire set of these ranges should be able to collectively represent every missing number between lower
and upper
. Therefore, the returned list of ranges should be non-overlapping, cover every missing number, and exclude every number present in nums
.
Examples
Example 1
Input:
nums = [0,1,3,50,75], lower = 0, upper = 99
Output:
[[2,2],[4,49],[51,74],[76,99]]
Explanation:
The ranges are: [2,2] [4,49] [51,74] [76,99]
Example 2
Input:
nums = [-1], lower = -1, upper = -1
Output:
[]
Explanation:
There are no missing ranges since there are no missing numbers.
Constraints
-109 <= lower <= upper <= 109
0 <= nums.length <= 100
lower <= nums[i] <= upper
- All the values of
nums
are unique.
Approach and Intuition
To tackle this problem, follow these logical steps:
- Start by initializing the starting point of a potential missing range, which we will call
nextExpectedNumber
, initialized tolower
. - Iterate through the sorted array
nums
:- For each number in
nums
, determine if there is a gap betweennextExpectedNumber
(the next number you expect in a perfectly consecutive sequence starting fromlower
) and the current number in the array minus one. This gap indicates missing numbers. - Identify and record these gaps as ranges. After processing a number from
nums
, updatenextExpectedNumber
to that number plus one.
- For each number in
- Upon completion of the array iteration, it is possible that there are still missing numbers from the last number in
nums
toupper
. IfnextExpectedNumber
is less than or equal toupper
, these numbers are missing, and you should record this final range. - The construction of ranges during iteration ensures they are sorted and non-overlapping as required.
By following the outlined steps, you can efficiently find all missing ranges without redundant computations, leveraging the sorted nature of nums
and the defined continuity of the range from lower
to upper
.
Solutions
- C++
- Java
- C
- JavaScript
- Python
class Solution {
public:
vector<vector<int>> getMissingIntervals(vector<int>& nums, int lower, int upper) {
int len = nums.size();
vector<vector<int>> missingIntervals;
if (len == 0) {
missingIntervals.push_back(vector<int>{lower, upper});
return missingIntervals;
}
if (lower < nums[0]) {
missingIntervals.push_back(vector<int>{lower, nums[0] - 1});
}
for (int i = 0; i < len - 1; i++) {
if (nums[i + 1] - nums[i] <= 1) {
continue;
}
missingIntervals.push_back(vector<int>{nums[i] + 1, nums[i + 1] - 1});
}
if (upper > nums[len - 1]) {
missingIntervals.push_back(vector<int>{nums[len - 1] + 1, upper});
}
return missingIntervals;
}
};
The provided C++ solution aims to identify missing ranges within a given array of integers, where the missing ranges are those intervals that do not include any elements from the array but fall within a specified range from lower
to upper
.
- At the beginning, the solution defines a method
getMissingIntervals
that takes an array of integersnums
and two integerslower
andupper
. - The method first determines the length of the
nums
array. Ifnums
is empty, it immediately returns the interval fromlower
toupper
as the missing range. - If the array isn't empty and the
lower
bound is less than the first element of the array, it includes the range fromlower
to one less than the first element as a missing interval. - The solution iterates through the array and checks consecutive elements. If the gap between two consecutive numbers is greater than 1, the interval between these numbers minus the boundaries is identified as missing and added to the result list.
- After iterating through the array, if
upper
is greater than the last element, it adds the range from one more than the last element innums
toupper
as a missing range. - Finally, the method returns a list of vectors, each representing a missing range.
This function provides an efficient way to identify and return all missing numerical ranges between given boundaries, considering gaps within a sorted array of numbers.
class Solution {
public List<List<Integer>> getMissingRanges(int[] values, int start, int end) {
List<List<Integer>> ranges = new ArrayList<>();
int size = values.length;
if (size == 0) {
ranges.add(Arrays.asList(start, end));
return ranges;
}
if (start < values[0]) {
ranges.add(Arrays.asList(start, values[0] - 1));
}
for (int i = 0; i < size - 1; i++) {
if (values[i + 1] - values[i] > 1) {
ranges.add(Arrays.asList(values[i] + 1, values[i + 1] - 1));
}
}
if (end > values[size - 1]) {
ranges.add(Arrays.asList(values[size - 1] + 1, end));
}
return ranges;
}
}
The Java solution presented focuses on identifying and listing all missing ranges in a sorted array of integers. Given two integers, start
and end
, which define the inclusive boundaries of a range, the function determines all the sub-ranges that are not covered by the integers in the values
array. Here's how the solution operates:
- A new
ArrayList
of typeList<List<Integer>>
namedranges
is created to store the missing ranges. - The function first checks if the
values
array is empty. If true, it adds the complete range fromstart
toend
toranges
since no numbers are present to create any sub-ranges. - If the
values
array is not empty, the function assesses the space before the first element ofvalues
:- If the
start
value is less than the first value invalues
, then the range fromstart
tovalues[0]-1
is added toranges
.
- If the
- A loop then iterates over the
values
array (up to the second last element) checking for gaps between consecutive elements:- If the difference between the current element and the next is greater than 1, it identifies a missing range which is then added to
ranges
.
- If the difference between the current element and the next is greater than 1, it identifies a missing range which is then added to
- Post loop, the function examines the difference between the last element of
values
and theend
:- If the last value in
values
is less thanend
, the range fromvalues[size - 1] + 1
toend
is added to theranges
.
- If the last value in
- Finally, the
ranges
list containing all identified missing sub-ranges is returned.
This solution is optimal and concise, providing a clear method to identify all gaps within any given range, accommodating for arrays of any size including empty arrays. It utilizes basic array manipulation and conditional checks to determine the presence of gaps efficiently.
struct Interval {
int low, high;
};
struct Interval** detectMissingIntervals(int* elements, int elementCount, int lowBound, int highBound,
int* sizeOfReturn, int** sizeColumns) {
int totalElements = elementCount;
struct Interval** missingIntervals = malloc((totalElements + 2) * sizeof(struct Interval*));
*sizeColumns = malloc((totalElements + 2) * sizeof(int));
*sizeOfReturn = 0;
if (totalElements == 0) {
missingIntervals[*sizeOfReturn] = malloc(2 * sizeof(int));
missingIntervals[*sizeOfReturn]->low = lowBound;
missingIntervals[*sizeOfReturn]->high = highBound;
(*sizeColumns)[*sizeOfReturn] = 2;
(*sizeOfReturn)++;
return missingIntervals;
}
if (lowBound < elements[0]) {
missingIntervals[*sizeOfReturn] = malloc(2 * sizeof(int));
missingIntervals[*sizeOfReturn]->low = lowBound;
missingIntervals[*sizeOfReturn]->high = elements[0] - 1;
(*sizeColumns)[*sizeOfReturn] = 2;
(*sizeOfReturn)++;
}
for (int idx = 0; idx < totalElements - 1; idx++) {
if (elements[idx + 1] - elements[idx] <= 1) {
continue;
}
missingIntervals[*sizeOfReturn] = malloc(2 * sizeof(int));
missingIntervals[*sizeOfReturn]->low = elements[idx] + 1;
missingIntervals[*sizeOfReturn]->high = elements[idx + 1] - 1;
(*sizeColumns)[*sizeOfReturn] = 2;
(*sizeOfReturn)++;
}
if (highBound > elements[totalElements - 1]) {
missingIntervals[*sizeOfReturn] = malloc(2 * sizeof(int));
missingIntervals[*sizeOfReturn]->low = elements[totalElements - 1] + 1;
missingIntervals[*sizeOfReturn]->high = highBound;
(*sizeColumns)[*sizeOfReturn] = 2;
(*sizeOfReturn)++;
}
return missingIntervals;
}
The provided C code defines a function designed to identify missing ranges in a sequence of numbers. Here's how it works:
Function Definition:
detectMissingIntervals
takes several parameters: a pointer to anelements
array of integers, anelementCount
indicating the number of elements, boundary valueslowBound
andhighBound
, pointerssizeOfReturn
andsizeColumns
to hold the size of the resulting array and its columns, respectively.Memory Allocation: Initializes an array of
Interval
structures to store the missing intervals and the sizes of columns in the result.Handling Empty Element List: If no elements are provided, the function sets the missing interval to the entire range from
lowBound
tohighBound
and updates the return size.Finding Missing Intervals:
- Checks if there are any gaps before the first element and after the last element in the sequence.
- Iterates through the
elements
array to determine gaps between consecutive elements that are larger than one, thereby identifying missing intervals.
Memory Allocation For Each Missing Interval: For each identified interval, it allocates memory and assigns the interval's lower and upper bounds before updating the return size.
Return the Result: Returns the dynamically allocated array of intervals, allowing the caller to access the missing ranges.
Keep in mind that the memory allocated for storing these intervals and the return size information needs to be managed (i.e., freed) externally to avoid memory leaks.ing or adding debug logs at key points in the code can help trace the value changes and behavior, crucial for validating modifications or enhancements.
var calculateMissingRanges = function (values, start, end) {
let length = values.length;
let missing = [];
if (length === 0) {
missing.push([start, end]);
return missing;
}
// Filling missed ranges from the low boundary to the first element
if (start < values[0]) {
missing.push([start, values[0] - 1]);
}
// Missing ranges between consecutive elements
for (let index = 0; index < length - 1; index++) {
if (values[index + 1] - values[index] <= 1) {
continue;
}
missing.push([values[index] + 1, values[index + 1] - 1]);
}
// Missing numbers after the last element till the upper boundary
if (end > values[length - 1]) {
missing.push([values[length - 1] + 1, end]);
}
return missing;
};
The provided JavaScript function, calculateMissingRanges
, efficiently finds the missing ranges of numbers between a specified start and end, against a list of sorted values. Here's a concise understanding of how it operates:
- First, it initializes a variable,
missing
, to store the resultant ranges of missing numbers. - It checks if the
values
array is empty. If so, the entire range fromstart
toend
is missing, and it returns this range. - It handles the scenario where the range starts before the first element in the
values
array by adding the range fromstart
to one less than the first element invalues
. - Next, it loops through the
values
array, examining gaps between consecutive numbers that are greater than one, signaling a missing range. It adds these ranges to themissing
array. - It ends by checking if there are missing numbers after the last element up to the
end
. If so, it adds this range from one greater than the last number invalues
toend
. - The function returns the list of missing ranges.
This implementation offers a straightforward approach to determine the absent sequences in a given numerical interval, making it suitable for various applications that require such numerical gap analyses.
class Solution:
def findGaps(self, numbers: List[int], low: int, high: int) -> List[List[int]]:
length = len(numbers)
gaps = []
if length == 0:
gaps.append([low, high])
return gaps
# Handle the gap before the first number
if low < numbers[0]:
gaps.append([low, numbers[0] - 1])
# Handle gaps between numbers in the array
for index in range(length - 1):
if numbers[index + 1] - numbers[index] > 1:
gaps.append([numbers[index] + 1, numbers[index + 1] - 1])
# Handle the gap after the last number
if high > numbers[-1]:
gaps.append([numbers[-1] + 1, high])
return gaps
The solution provided involves finding the missing ranges in a given sorted list of integers, denoted by the input parameters numbers
, low
, and high
. The function findGaps
implemented in Python ensures you identify those missing sequences efficiently.
- Start by initializing a list
gaps
to store the missing ranges as sublists. - Check if the
numbers
list is empty; if so, the entire range fromlow
tohigh
is missing, and this range is appended togaps
before returning it. - Address the potential gap that might exist before the first number in the list. If the lower bound,
low
, is less than the first element ofnumbers
, append the range fromlow
tonumbers[0] - 1
togaps
. - Iterate through the given numbers to find and append gaps between consecutive numbers. Specifically, for each pair of consecutive elements where the difference is greater than one, append the range starting from
numbers[index] + 1
tonumbers[index + 1] - 1
togaps
. - Identify and append the missing range after the last number if necessary. If the upper bound,
high
, is greater than the last element ofnumbers
, append the range fromnumbers[-1] + 1
tohigh
togaps
. - Return the completed
gaps
list that now contains all missing ranges.
By following these steps, the function effectively fills the gaps with each missing range, thus providing a full view of all absent sequences between the specified bounds.
No comments yet.