Missing Ranges

Question:
Given a sorted integer array where the range of elements are [0, 99] inclusive, return its missing ranges.
For example, given [0, 1, 3, 50, 75], return [“2”, “4->49”, “51->74”, “76->99”]

Example Questions Candidate Might Ask:
Q: What if the given array is empty?
A: Then you should return [“0->99”] as those ranges are missing.
Q: What if the given array contains all elements from the ranges?
A: Return an empty list, which means no range is missing.

Solution:
Compare the gap between two neighbor elements and output its range, simple as that
right? This seems deceptively easy, except there are multiple edge cases to consider, such
as the first and last element, which does not have previous and next element respectively.
Also, what happens when the given array is empty? We should output the range “0->99”.

As it turns out, if we could add two “artificial” elements, –1 before the first element and
100 after the last element, we could avoid all the above pesky cases.

Further Thoughts:
i. List out test cases.
ii. You should be able to extend the above cases not only for the range [0,99],
but any arbitrary range [start, end].

public List<String> findMissingRanges(int[] vals, int start, int end) {
   List<String> ranges = new ArrayList<>();
   int prev = start - 1;
   for (int i = 0; i <= vals.length; i++) {
      int curr = (i == vals.length) ? end + 1 : vals[i];
      if (curr - prev >= 2) {
         ranges.add(getRange(prev + 1, curr - 1));
      }
      prev = curr;
   }
   return ranges;
}
private String getRange(int from, int to) {
    return (from == to) ? String.valueOf(from) : from + "->" + to;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值