Problem
int[] nums = {2, 3, 5, 10, 75};
int lower = 0, upper = 99;
Output : [0->1,4,6->49,51-74,76->99]
Code
import java.util.ArrayList;
import java.util.List;
public class MissingRange {
public List<String> solution(int low, int upper, int[] nums) {
List<String> result = new ArrayList<>();
if(nums == null || nums.length == 0) return result;
if (low < nums[0]) {
result.add(makeRange(low, nums[0]-1));
}
for (int i = 0; i < nums.length-1; i++) {
if (nums[i] != nums[i + 1] && nums[i] + 1 < nums[i+1]) {
result.add(makeRange(nums[i]+1, nums[i+1]-1));
}
}
if (nums[nums.length - 1] < upper) {
result.add(makeRange(nums[nums.length - 1]+1, upper));
}
return result;
}
public List<String> solution2(int low, int upper, int[] nums) {
List<String> result = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
int start, end;
if (i == 0)
start = low;
else
start = nums[i-1]+1;
if(start == nums[i]) continue;
end = nums[i] - 1;
result.add(makeRange(start, end));
}
if (nums[nums.length - 1] < upper) {
result.add(makeRange(nums[nums.length - 1] + 1, upper));
}
return result;
}
private String makeRange(int low, int high) {
return low == high ? String.valueOf(low) : (low + "->" + high);
}
public static void main(String[] args) {
int[] nums = new int[]{2,3,5,50,75};
MissingRange problem = new MissingRange();
System.out.println(problem.solution(0, 99, nums));
System.out.println(problem.solution2(0, 99, nums));
}
}