703570. Missing Intervals

Medium

Missing Intervals

Slug: missing-intervals3058 Difficulty: Medium Id: 703570 Topic Tags: Arrays, STL, Data Structures Company Tags: Google

Summary

The problem is about finding all intervals in a given array of integers that are not present in the original sequence. The input array contains unique integers, and we need to find the missing intervals between these numbers.

Detailed Explanation

To solve this problem, we can iterate through the sorted array and keep track of the previous number. For each element, we calculate the difference between the current number and the previous one, which represents the size of the interval. If the current number is not equal to the previous number plus the interval size, it means that there was a missing interval.

Here's a step-by-step breakdown of the solution:

  1. Sort the input array in ascending order.
  2. Initialize variables prev and interval_size to the first element of the array and 0, respectively.
  3. Iterate through the sorted array:
    • For each element curr, calculate interval_size as the difference between curr and prev.
    • If curr is not equal to prev + interval_size, it means that there was a missing interval.
    • Print or store this missing interval (i.e., the range from prev + 1 to curr - 1).
  4. Update prev to curr.

The time complexity of this algorithm is O(n log n) due to the sorting step, where n is the number of elements in the input array. The space complexity is O(1), as we only use a constant amount of space to store the previous element and interval size.

Optimized Solutions

Java

java
public class MissingIntervals {
    public static void findMissingIntervals(int[] arr) {
        Arrays.sort(arr);
        int prev = arr[0];
        for (int i = 1; i < arr.length; i++) {
            int curr = arr[i];
            int intervalSize = curr - prev;
            if (curr != prev + intervalSize) {
                System.out.println("Missing interval: [" + (prev + 1) + ", " + (curr - 1) + "]");
            }
            prev = curr;
        }
    }
}

Python

View on GeeksforGeeks

Not available

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.