Leetcode 228: Summary Ranges

grid47
grid47
Exploring patterns and algorithms
Oct 15, 2024 5 min read

A range of numbers with each segment gently highlighted, showing the summarized range.
Solution to LeetCode 228: Summary Ranges Problem

You are given a sorted array of unique integers. Your task is to group consecutive numbers into ranges and return a sorted list of these ranges. A range [a,b] includes all integers from a to b (inclusive). Each range should be represented as ‘a->b’ if a != b or ‘a’ if a == b.
Problem
Approach
Steps
Complexity
Input: A sorted array of unique integers.
Example: Input: nums = [-3,-2,-1,1,2,5]
Constraints:
• The array length is in the range [0, 20].
• All values in the array are unique.
• The values are sorted in ascending order.
• Each integer lies in the range [-2^31, 2^31 - 1].
Output: A sorted list of ranges that cover all the numbers in the array exactly, with each range formatted as 'a->b' or 'a'.
Example: Output: ['-3->-1','1->2','5']
Constraints:
• Each number in the input array must be included in exactly one range.
• Ranges must not include any integers outside the input array.
Goal: Identify consecutive sequences of numbers and group them into ranges.
Steps:
• Initialize a pointer to traverse the array.
• For each element, determine the start of a range.
• Continue iterating until the end of the current range is reached (next number is not consecutive).
• Add the range to the result list in the appropriate format ('a->b' or 'a').
• Repeat until all elements are processed.
Goal: The problem is constrained as follows:
Steps:
• Input array length is at most 20.
• Values are sorted in ascending order.
• Each value is unique.
• Values lie within the 32-bit signed integer range.
Assumptions:
• The input array is non-null and adheres to the constraints.
• Consecutive values are integers differing by exactly 1.
Input: Input: nums = [1,2,3,5,7,8,10]
Explanation: The ranges are: [1,3] -> '1->3', [5,5] -> '5', [7,8] -> '7->8', [10,10] -> '10'. Output: ['1->3','5','7->8','10'].

Input: Input: nums = [0,2,3,6]
Explanation: The ranges are: [0,0] -> '0', [2,3] -> '2->3', [6,6] -> '6'. Output: ['0','2->3','6'].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus