Skip to content

Commit ce08764

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 228 Summary Ranges
1 parent 96b7f0c commit ce08764

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
4242
- [202 Happy Number](https://leetcode.com/problems/happy-number/description/)
4343
- [205 Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/description/)
4444
- [219 Contains Duplicates II](https://leetcode.com/problems/contains-duplicate-ii/description/)
45+
- [228 Summary Ranges](https://leetcode.com/problems/summary-ranges/description/)
4546
- [242 Valid Anagram](https://leetcode.com/problems/valid-anagram/description/)
4647
- [290 Word Pattern](https://leetcode.com/problems/word-pattern/description/)
4748
- [383 Ransom Note](https://leetcode.com/problems/ransom-note/description/)
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def summaryRanges(self, nums: List[int]) -> List[str]:
6+
"""
7+
You are given a sorted unique integer array nums.
8+
9+
A range [a,b] is the set of all integers from a to b (inclusive).
10+
11+
Return the smallest sorted list of ranges that cover all the numbers in the array exactly.
12+
That is, each element of nums is covered by exactly one of the ranges, and there is no
13+
integer x such that x is in one of the ranges but not in nums.
14+
15+
Each range [a,b] in the list should be output as:
16+
- "a->b" if a != b
17+
- "a" if a == b
18+
"""
19+
ranges = []
20+
for left, n in enumerate(nums):
21+
if n - 1 not in nums:
22+
length = 0
23+
right = left
24+
while (n + length) in nums:
25+
length += 1
26+
right += 1
27+
if left == right - 1:
28+
ranges.append(f"{nums[left]}")
29+
else:
30+
ranges.append(f"{nums[left]}->{nums[right-1]}")
31+
return ranges

tests/test_228_summary_ranges.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._228_summary_ranges import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["nums", "expected"],
10+
argvalues=[
11+
([0, 1, 2, 4, 5, 7], ["0->2", "4->5", "7"]),
12+
([0, 2, 3, 4, 6, 8, 9], ["0", "2->4", "6", "8->9"]),
13+
],
14+
)
15+
def test_func(nums: List[int], expected: List[str]):
16+
ranges = Solution().summaryRanges(nums)
17+
assert ranges == expected

0 commit comments

Comments
 (0)