2655. Find Maximal Uncovered Ranges

ArraySorting

Explanation:

Given a list of ranges, we need to find the maximal uncovered ranges. An uncovered range is a continuous range of integers that does not intersect with any of the given ranges.

To solve this problem, we can follow these steps:

  1. Sort the given ranges based on their start points.
  2. Initialize a variable max_end to keep track of the maximum end point encountered while iterating through the ranges.
  3. Iterate through the sorted ranges:
    • If the current range's start point is greater than max_end + 1, then we have found an uncovered range from max_end + 1 to the start point of the current range.
    • Update max_end to the maximum of its current value and the end point of the current range.
  4. If max_end is less than the maximum integer value, then the range from max_end + 1 to the maximum integer value is also an uncovered range.

Time Complexity: O(nlogn) where n is the number of ranges due to the sorting process. Space Complexity: O(1) as we are using constant extra space.

:

import java.util.*;

class Solution {
    public List<List<Integer>> findMaximalUncoveredRanges(int[][] ranges) {
        List<List<Integer>> result = new ArrayList<>();
        
        Arrays.sort(ranges, (a, b) -> a[0] - b[0]);
        
        int maxEnd = Integer.MIN_VALUE;
        
        for (int i = 0; i < ranges.length; i++) {
            if (ranges[i][0] > maxEnd + 1) {
                List<Integer> uncoveredRange = new ArrayList<>();
                uncoveredRange.add(maxEnd + 1);
                uncoveredRange.add(ranges[i][0] - 1);
                result.add(uncoveredRange);
            }
            maxEnd = Math.max(maxEnd, ranges[i][1]);
        }
        
        if (maxEnd < Integer.MAX_VALUE) {
            List<Integer> lastRange = new ArrayList<>();
            lastRange.add(maxEnd + 1);
            lastRange.add(Integer.MAX_VALUE);
            result.add(lastRange);
        }
        
        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.