LeetCode 228: Summary Ranges

Array

Problem Description

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.

Solutions

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

Loading editor...