HomeLeetcode228. Summary Ranges - Leetcode Solutions

228. Summary Ranges – Leetcode Solutions

Description

You are given a sorted unique integer array nums.

range [a,b] is the set of all integers from a to b (inclusive).

Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.

Each range [a,b] in the list should be output as:

  • "a->b" if a != b
  • "a" if a == b

Examples:

Example 1:

Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: The ranges are:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"

Example 2:

Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: The ranges are:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"

Solution in Python

Python
class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        # Initialize an empty list to store the resulting ranges
        result = []
        
        # If the input list is empty, return the empty result list
        if not nums:
            return result
        
        # Initialize the start of the first range
        start = nums[0]
        
        # Loop through the list of numbers, starting from the second element
        for i in range(1, len(nums)):
            # If the current number is not consecutive from the previous number
            if nums[i] != nums[i - 1] + 1:
                # If the start and the previous number are the same, it's a single number
                if start == nums[i - 1]:
                    result.append(f"{start}")
                else:
                    # Otherwise, it's a range from 'start' to the previous number
                    result.append(f"{start}->{nums[i - 1]}")
                # Update the start to the current number
                start = nums[i]
        
        # Add the last range or single number after the loop ends
        if start == nums[-1]:
            result.append(f"{start}")
        else:
            result.append(f"{start}->{nums[-1]}")
        
        return result

Explanation:

  1. Initialization:
    • result is initialized as an empty list that will store the resulting range strings.
    • start keeps track of the beginning of the current range.
  2. Empty Input Check:
    • If nums is an empty list, the function immediately returns the empty result.
  3. Main Loop:
    • The loop starts from the second element (i = 1) and compares each element with the previous one to check if they are consecutive.
    • If the current number is not consecutive (nums[i] != nums[i-1] + 1), it means the current range has ended:
      • If the start of the range is equal to the last number (start == nums[i-1]), it’s a single number, and we append it as a single value (e.g., "7").
      • If the range has more than one number, we append it as "start->end".
  4. Final Range Handling:
    • After the loop, the last range or number is added to the result.

Solution in Javascript

JavaScript
/**
 * @param {number[]} nums
 * @return {string[]}
 */
var summaryRanges = function(nums) {
    // Initialize an empty array to store the resulting ranges
    let result = [];
    
    // If the input array is empty, return the empty result array
    if (nums.length === 0) {
        return result;
    }
    
    // Initialize the start of the first range
    let start = nums[0];
    
    // Loop through the array of numbers, starting from the second element
    for (let i = 1; i < nums.length; i++) {
        // If the current number is not consecutive from the previous one
        if (nums[i] !== nums[i - 1] + 1) {
            // If the start and the previous number are the same, it's a single number
            if (start === nums[i - 1]) {
                result.push(`${start}`);
            } else {
                // Otherwise, it's a range from 'start' to the previous number
                result.push(`${start}->${nums[i - 1]}`);
            }
            // Update the start to the current number
            start = nums[i];
        }
    }
    
    // Add the last range or single number after the loop ends
    if (start === nums[nums.length - 1]) {
        result.push(`${start}`);
    } else {
        result.push(`${start}->${nums[nums.length - 1]}`);
    }
    
    // Return the result array containing the ranges
    return result;
};

Solution in Java

Java
import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<String> summaryRanges(int[] nums) {
        // Initialize an empty list to store the resulting ranges
        List<String> result = new ArrayList<>();
        
        // If the input array is empty, return the empty result list
        if (nums.length == 0) {
            return result;
        }
        
        // Initialize the start of the first range
        int start = nums[0];
        
        // Loop through the array of numbers, starting from the second element
        for (int i = 1; i < nums.length; i++) {
            // If the current number is not consecutive from the previous one
            if (nums[i] != nums[i - 1] + 1) {
                // If start and the previous number are the same, it's a single number
                if (start == nums[i - 1]) {
                    result.add(Integer.toString(start));
                } else {
                    // Otherwise, it's a range from 'start' to the previous number
                    result.add(start + "->" + nums[i - 1]);
                }
                // Update the start to the current number
                start = nums[i];
            }
        }
        
        // Add the last range or single number after the loop ends
        if (start == nums[nums.length - 1]) {
            result.add(Integer.toString(start));
        } else {
            result.add(start + "->" + nums[nums.length - 1]);
        }
        
        // Return the result list containing the ranges
        return result;
    }
}

Solution in C#

C#
using System;
using System.Collections.Generic;

public class Solution {
    public IList<string> SummaryRanges(int[] nums) {
        // Initialize a list to store the resulting ranges
        List<string> result = new List<string>();
        
        // If the input array is empty, return the empty result list
        if (nums.Length == 0) {
            return result;
        }
        
        // Initialize the start of the first range
        int start = nums[0];
        
        // Loop through the array of numbers, starting from the second element
        for (int i = 1; i < nums.Length; i++) {
            // If the current number is not consecutive from the previous one
            if (nums[i] != nums[i - 1] + 1) {
                // If start and the previous number are the same, it's a single number
                if (start == nums[i - 1]) {
                    result.Add(start.ToString());
                } else {
                    // Otherwise, it's a range from 'start' to the previous number
                    result.Add(start + "->" + nums[i - 1]);
                }
                // Update the start to the current number
                start = nums[i];
            }
        }
        
        // Add the last range or single number after the loop ends
        if (start == nums[nums.Length - 1]) {
            result.Add(start.ToString());
        } else {
            result.Add(start + "->" + nums[nums.Length - 1]);
        }
        
        // Return the result list containing the ranges
        return result;
    }
}

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular