Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 228: Summary Ranges

Array

LeetCode 228 Solution 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 start and end to 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 end to the current number.
  • If there is a gap, add the range [start, end] to the result list.
  • Update start to 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.

LeetCode 228 Solutions in Java, C++, Python

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;
    }
}

Interactive Code Editor for LeetCode 228

Improve Your LeetCode 228 Solution

Use the editor below to refine the provided solution for LeetCode 228. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems