#228
Summary Ranges
EasyArrayArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a single pass through the array to group numbers into ranges. This approach is efficient because it only requires one iteration, making it faster and more suitable for larger datasets.
⚙️
Algorithm
4 steps- 1Step 1: Initialize an empty list to store ranges and set the start of the first range.
- 2Step 2: Iterate through the array, checking if the current number is consecutive to the previous number.
- 3Step 3: If it is not consecutive, finalize the current range and start a new one.
- 4Step 4: After the loop, finalize the last range.
solution.py20 lines
1# Full working Python code
2
3def summaryRanges(nums):
4 if not nums:
5 return []
6 ranges = []
7 start = nums[0]
8 for i in range(1, len(nums)):
9 if nums[i] != nums[i - 1] + 1:
10 if start == nums[i - 1]:
11 ranges.append(str(start))
12 else:
13 ranges.append(f'{start}->{nums[i - 1]}')
14 start = nums[i]
15 if start == nums[-1]:
16 ranges.append(str(start))
17 else:
18 ranges.append(f'{start}->{nums[-1]}')
19 return ranges
20ℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the array, checking each number once. The space complexity is O(n) for storing the resulting ranges.
- 1The input array is sorted and contains unique integers, which simplifies the logic for detecting ranges.
- 2Each range can be identified by checking if the current number is consecutive to the previous one.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.