Skip to content

Commit

Permalink
solve "228. Summary Ranges"
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Sep 17, 2024
1 parent 23f6d16 commit ca69b68
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .plan
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
Sep 17, 2024

* solve "228. Summary Ranges"

Sep 16, 2024

* re-solve question 28 using Knuth–Morris–Pratt
Expand Down
23 changes: 23 additions & 0 deletions src/summary_ranges.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class Solution:
def summaryRanges(self, nums: list[int]) -> list[str]:
if not nums:
return []

result: list[str] = []
left = right = nums[0]

def append() -> None:
if left == right:
result.append(f"{left}")
else:
result.append(f"{left}->{right}")

for i in range(1, len(nums)):
if nums[i] == right + 1:
right = nums[i]
else:
append()
left = right = nums[i]

append()
return result
14 changes: 14 additions & 0 deletions tests/test_summary_ranges.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import pytest

from src.summary_ranges import Solution


@pytest.mark.parametrize(
"expected,nums",
(
(["0->2", "4->5", "7"], [0, 1, 2, 4, 5, 7]),
(["0", "2->4", "6", "8->9"], [0, 2, 3, 4, 6, 8, 9]),
),
)
def test_solution(expected, nums):
assert expected == Solution().summaryRanges(nums)

0 comments on commit ca69b68

Please sign in to comment.