Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add explanation and solution for LeetCode problem 228 (Summary Ranges) #49

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
romankurnovskii wants to merge 1 commit into main
base: main
Choose a base branch
Loading
from pr-problem-228
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions explanations/228/en.md
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
## 228. Summary Ranges [Easy]

https://leetcode.com/problems/summary-ranges

## Description
You are given a **sorted unique** integer array `nums`.

A **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**

```tex
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"
```

**Constraints**
```tex
- 0 <= nums.length <= 20
- -2^31 <= nums[i] <= 2^31 - 1
- All the values of nums are unique
- nums is sorted in ascending order
```

## Explanation

### Strategy
Let's restate the problem: You're given a sorted array of unique integers, and you need to create a summary of consecutive ranges. The goal is to represent consecutive sequences as ranges (e.g., "0->2") and single numbers as themselves (e.g., "7").

This is an **array traversal problem** that requires identifying consecutive sequences and formatting them appropriately.

**What is given?** A sorted array of unique integers (up to 20 elements).

**What is being asked?** Create a list of ranges that cover all numbers exactly, representing consecutive sequences as ranges and single numbers as themselves.

**Constraints:** The array is small (up to 20 elements), sorted, and contains unique values.

**Edge cases:**
- Empty array
- Single element array
- Array with no consecutive sequences
- Array with all consecutive sequences

**High-level approach:**
The solution involves traversing the array and identifying consecutive sequences. When we find a break in the sequence, we format the range appropriately and continue.

**Decomposition:**
1. **Handle edge cases**: Empty array returns empty list
2. **Initialize variables**: Track start of current range and result list
3. **Traverse array**: Look for consecutive sequences
4. **Format ranges**: Convert consecutive sequences to appropriate string format
5. **Handle final range**: Don't forget the last range when loop ends

**Brute force vs. optimized strategy:**
- **Brute force**: Check each possible range combination. This is inefficient.
- **Optimized**: Single pass through the array, identifying consecutive sequences as we go. This takes O(n) time.

### Steps
Let's walk through the solution step by step using the first example: `nums = [0,1,2,4,5,7]`

**Step 1: Handle edge case**
- Array is not empty, continue

**Step 2: Initialize variables**
- `start = 0` (start of current range)
- `result = []` (list to store ranges)

**Step 3: Traverse array looking for consecutive sequences**
- `i = 0`: `nums[0] = 0`
- Start new range: `start = 0`
- `i = 1`: `nums[1] = 1`
- Check if consecutive: `1 == 0 + 1` ✓
- Continue current range
- `i = 2`: `nums[2] = 2`
- Check if consecutive: `2 == 1 + 1` ✓
- Continue current range
- `i = 3`: `nums[3] = 4`
- Check if consecutive: `4 == 2 + 1` ✗
- Break in sequence! Format range [0,2] as "0->2"
- Add to result: `result = ["0->2"]`
- Start new range: `start = 3`
- `i = 4`: `nums[4] = 5`
- Check if consecutive: `5 == 4 + 1` ✓
- Continue current range
- `i = 5`: `nums[5] = 7`
- Check if consecutive: `7 == 5 + 1` ✗
- Break in sequence! Format range [4,5] as "4->5"
- Add to result: `result = ["0->2", "4->5"]`
- Start new range: `start = 5`

**Step 4: Handle final range**
- Loop ended, need to handle the last range [7,7]
- Since start == end (7 == 7), format as "7"
- Add to result: `result = ["0->2", "4->5", "7"]`

**Step 5: Return result**
- Final result: `["0->2","4->5","7"]`

**Why this works:**
By traversing the array once and checking for consecutive numbers, we can identify ranges efficiently. The key insights are:
1. A break in the sequence occurs when `nums[i] != nums[i-1] + 1`
2. Single numbers (where start == end) are formatted as "a"
3. Ranges (where start != end) are formatted as "a->b"

> **Note:** The key insight is identifying consecutive sequences by checking if each number is exactly one more than the previous number. This allows us to build ranges efficiently in a single pass.

**Time Complexity:** O(n) - we visit each element once
**Space Complexity:** O(n) - we need to store the result list
41 changes: 41 additions & 0 deletions solutions/228/01.py
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
def summaryRanges(nums):
"""
Create a summary of ranges from a sorted array of unique integers.

Args:
nums: List[int] - Sorted array of unique integers

Returns:
List[str] - List of range strings
"""
# Handle edge case
if not nums:
return []

result = []
start = 0

# Traverse array looking for consecutive sequences
for i in range(1, len(nums)):
# Check if current number is consecutive to previous
if nums[i] != nums[i-1] + 1:
# Break in sequence, format the range
if start == i - 1:
# Single number
result.append(str(nums[start]))
else:
# Range of numbers
result.append(f"{nums[start]}->{nums[i-1]}")

# Start new range
start = i

# Handle the final range
if start == len(nums) - 1:
# Single number
result.append(str(nums[start]))
else:
# Range of numbers
result.append(f"{nums[start]}->{nums[-1]}")

return result

AltStyle によって変換されたページ (->オリジナル) /