703442. Missing ranges of numbers
Missing Ranges of Numbers
Slug: missing-ranges-of-numbers1019 Difficulty: Easy Id: 703442 Topic Tags: Arrays, Data Structures Company Tags: None
Summary
The problem is about finding the missing ranges of numbers in a given array. The input array contains consecutive integers with some ranges missing. You need to find all the missing ranges of numbers.
Detailed Explanation
To solve this problem, we can iterate through the input array and keep track of the current range of numbers. When we encounter a gap or a missing number, we add it to our result list. Here's a step-by-step breakdown:
- Initialize an empty list
resultto store the missing ranges. - Iterate through the input array from left to right.
- For each element in the array:
- If the current element is not equal to the previous element + 1, it means there is a gap or a missing number. Calculate the range of this missing number and add it to
result. - Update the previous element as the current element.
- If the current element is not equal to the previous element + 1, it means there is a gap or a missing number. Calculate the range of this missing number and add it to
- After iterating through the entire array, return the
resultlist.
Here's an ASCII art diagram representing the input array:
0 1 2 3 5 6 8 9
In this example, the missing range is [4].
The time complexity of this algorithm is O(n), where n is the length of the input array. The space complexity is O(k), where k is the number of missing ranges.
Optimized Solutions
Java
import java.util.ArrayList;
import java.util.List;
public class MissingRanges {
public List<String> findMissingRanges(int[] nums) {
List<String> result = new ArrayList<>();
if (nums.length == 0) {
return result.add("0-0");
}
int start = nums[0];
for (int i = 1; i <= nums.length; i++) {
if (i == nums.length || nums[i] - 1 != start) {
String range = start + "-" + (i - 1);
if (!range.equals("0-0")) {
result.add(range);
}
start = nums[i];
}
}
return result;
}
}