LeetCode 228: Summary Ranges Solution
Master LeetCode problem 228 (Summary Ranges), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
228. Summary Ranges
Problem Explanation
Explanation
To solve this problem, we can iterate through the input array and keep track of the start and end of each range. Whenever there is a gap in the sequence, we add the current range to the result. We handle the cases where a range has a single number separately. Finally, we return the list of ranges as strings.
- Initialize an empty list to store the result ranges.
- Initialize variables
startandendto track the start and end of the current range. - Iterate through the input array.
- If the current number is consecutive with the previous number, update the
endto the current number. - If there is a gap, add the range [start, end] to the result list.
- Update
startto the current number. - Handle the case where a range has a single number.
- Add the final range to the result list.
- Convert the ranges to the required format and return.
Time Complexity: O(n) where n is the number of elements in the input array. Space Complexity: O(1) excluding the space required for the output.
Solution Code
class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
return result;
}
int start = nums[0];
int end = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] == end + 1) {
end = nums[i];
} else {
if (start == end) {
result.add(Integer.toString(start));
} else {
result.add(start + "->" + end);
}
start = end = nums[i];
}
}
if (start == end) {
result.add(Integer.toString(start));
} else {
result.add(start + "->" + end);
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 228 (Summary Ranges)?
This page provides optimized solutions for LeetCode problem 228 (Summary Ranges) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 228 (Summary Ranges)?
The time complexity for LeetCode 228 (Summary Ranges) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 228 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 228 in Java, C++, or Python.