The Summary Ranges solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Summary Ranges
C++, Python and TypeScript solutions for Summary Ranges.
Solution files
Python•summary-ranges/synced-solution.py
def summaryRanges(nums: list[int]) -> list[str]:
result = []
i = 0
while i < len(nums):
start = nums[i]
while i + 1 < len(nums) and nums[i + 1] == nums[i] + 1:
i += 1
end = nums[i]
if start == end:
result.append(str(start))
else:
result.append(f"{start}->{end}")
i += 1
return result
C++•summary-ranges/synced-solution.cpp
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> result;
int i = 0;
while (i < nums.size()) {
long long start = nums[i];
while (i + 1 < nums.size() && (long long)nums[i + 1] == nums[i] + 1) {
i++;
}
long long end = nums[i];
if (start == end) {
result.push_back(to_string(start));
} else {
result.push_back(to_string(start) + "->" + to_string(end));
}
i++;
}
return result;
}
};
TypeScript•summary-ranges/synced-solution.ts
function summaryRanges(nums: number[]): string[] {
const result: string[] = [];
let i = 0;
while (i < nums.length) {
const start = nums[i];
while (i + 1 < nums.length && nums[i + 1] === nums[i] + 1) {
i++;
}
const end = nums[i];
if (start === end) {
result.push(String(start));
} else {
result.push(`${start}->${end}`);
}
i++;
}
return result;
}