703442. Missing ranges of numbers

Easy

Missing Ranges of Numbers

Slug: missing-ranges-of-numbers1019 Difficulty: Easy Id: 703442 Topic Tags: Arrays, Data Structures Company Tags: None

Summary

The problem is about finding the missing ranges of numbers in a given array. The input array contains consecutive integers with some ranges missing. You need to find all the missing ranges of numbers.

Detailed Explanation

To solve this problem, we can iterate through the input array and keep track of the current range of numbers. When we encounter a gap or a missing number, we add it to our result list. Here's a step-by-step breakdown:

  1. Initialize an empty list result to store the missing ranges.
  2. Iterate through the input array from left to right.
  3. For each element in the array:
    • If the current element is not equal to the previous element + 1, it means there is a gap or a missing number. Calculate the range of this missing number and add it to result.
    • Update the previous element as the current element.
  4. After iterating through the entire array, return the result list.

Here's an ASCII art diagram representing the input array:

0 1 2 3 5 6 8 9

In this example, the missing range is [4].

The time complexity of this algorithm is O(n), where n is the length of the input array. The space complexity is O(k), where k is the number of missing ranges.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.ArrayList;
import java.util.List;

public class MissingRanges {
    public List<String> findMissingRanges(int[] nums) {
        List<String> result = new ArrayList<>();
        if (nums.length == 0) {
            return result.add("0-0");
        }
        
        int start = nums[0];
        for (int i = 1; i <= nums.length; i++) {
            if (i == nums.length || nums[i] - 1 != start) {
                String range = start + "-" + (i - 1);
                if (!range.equals("0-0")) {
                    result.add(range);
                }
                start = nums[i];
            }
        }
        
        return result;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.