Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

163. Missing Ranges

Array

Explanation:

Given a sorted integer array and a lower and upper bound, the task is to find all missing ranges in the array within the specified lower and upper bounds. A missing range is defined as a contiguous sequence of numbers between the lower and upper bounds that are not present in the array.

To solve this problem:

  1. Iterate through the array and compare each element with its previous element to find missing ranges.
  2. If the difference between two consecutive elements is greater than 1, a missing range exists.
  3. Add the missing range to the result list if it lies within the specified lower and upper bounds. :
import java.util.*;

class Solution {
    public List<String> findMissingRanges(int[] nums, int lower, int upper) {
        List<String> result = new ArrayList<>();
        long start = (long) lower - 1; // To handle the case where lower = Integer.MIN_VALUE
        for (int i = 0; i <= nums.length; i++) {
            long end = (i < nums.length) ? (long) nums[i] : (long) upper + 1; // To handle the case where upper = Integer.MAX_VALUE
            if (end - start >= 2) {
                if (end - start == 2) {
                    result.add(String.valueOf(start + 1));
                } else {
                    result.add(String.valueOf(start + 1) + "->" + String.valueOf(end - 1));
                }
            }
            start = end;
        }
        return result;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.