LeetCode – Summary Ranges (Java)

Given a sorted integer array without duplicates, return the summary of its ranges for consecutive numbers.

For example, given [0,1,2,4,5,7], return [“0->2″,”4->5″,”7”].

Analysis

When iterating over the array, two values need to be tracked: 1) the first value of a new range and 2) the previous value in the range.

Java Solution

public List<String> summaryRanges(int[] nums) {
    List<String> result = new ArrayList<String>();
 
    if(nums == null || nums.length==0)
        return result;
 
    if(nums.length==1){
        result.add(nums[0]+"");
    }
 
    int pre = nums[0]; // previous element   
    int first = pre; // first element of each range
 
    for(int i=1; i<nums.length; i++){
            if(nums[i]==pre+1){
                if(i==nums.length-1){
                    result.add(first+"->"+nums[i]);
                }
            }else{
                if(first == pre){
                    result.add(first+"");
                }else{
                    result.add(first + "->"+pre);   
                }
 
                if(i==nums.length-1){
                    result.add(nums[i]+"");
                }
 
                first = nums[i];
            }
 
            pre = nums[i];
    }
 
    return result;
}

11 thoughts on “LeetCode – Summary Ranges (Java)”

  1. arr=[0,1,2,4,5,6,7,8]

    i=1
    j=0

    while i{arr[i-1]})”)
    j=i
    i+=1

    #put last range
    ans.append(f”({arr[j]}->{arr[len(arr)-1]}”)

    print(ans)

  2. O(n) Python3 Solution

    class Solution:
    def _makeInterval(self, start, end):
    return "{}->{}".format(start, end) if start != end else "{}".format(start)

    def summaryRanges(self, nums: List[int]) -> List[str]:
    ans = []
    if len(nums) == 0:
    return ans
    intervalStart, intervalEnd = nums[0], nums[0]
    for i in range(1, len(nums)):
    if nums[i] == intervalEnd + 1:
    intervalEnd += 1
    else:
    ans.append(self._makeInterval(intervalStart, intervalEnd))
    intervalStart, intervalEnd = nums[i], nums[i]
    ans.append(self._makeInterval(intervalStart, intervalEnd))
    return ans

  3. Given a sorted integer array without duplicates, return the summary of its ranges for consecutive numbers.

    ——

    could someone put explanation in English? and why given [0,1,2,4,5,7], return [“0->2″,”4->5″,”7”].

    author is amazing sloppy w/ words!!

  4. Might be more straightforward?

    static List getSummaryRanges(int[] in) {
    if(in ==null || in.length == 0) {
    return null;
    }

    int i = 1;
    int start = in[0];
    int end = in[0];
    List list = new LinkedList();
    while(i “+start+” end : “+end);
    start = in[i];
    end = in[i];
    }
    i++;
    }

    list.add(“first -> “+start+” end : “+end);

    return list;
    }

  5. I have a very easy to understand solution below:

    public class SummaryRanges {

    public static List ranges(int[] a) {
    List list = new ArrayList();
    int lo = 0;
    int hi = 0;
    for (int i = 1; i < a.length; i++) {
    if (a[i] – a[i – 1] == 1) {
    hi++;
    } else {
    constructResult(a, list, lo, hi);
    lo = i;
    hi = i;
    }
    }
    constructResult(a, list, lo, hi);
    return list;
    }

    private static void constructResult(int[] a, List list, int lo, int hi) {
    if (lo == hi) {
    list.add(String.valueOf(a[lo]));
    } else {
    list.add(a[lo] + “–>” + a[hi]);
    }
    }

    public static void main(String[] args) {

    //int[] a = { 0, 1, 2, 4, 5, 7 };
    //int[] a = { 3, 5, 6, 7, 8, 9 };
    int[] a = { 4, 6, 7, 8, 10, 12, 15, 16, 17, 25 };
    System.out.println(ranges(a));

    }
    }

  6. import java.util.*;

    public class Solution2 {

    public static void main(String[] args){

    Solution2 st = new Solution2();

    int[] nums = {0,2,3,4,5,6,8,10};

    List ret = st.getSummaryRanges(nums);

    for(String s : ret) System.out.println(s);

    }

    public List getSummaryRanges(int[] nums){

    if(nums == null || nums.length == 0) return null; // Edge cases. Error scenarios

    List ret = new ArrayList();

    boolean start = false;

    String range = “”;

    for(int i=0;i<nums.length;i++){

    if(i”;

    start = true;

    }

    continue;

    }

    else{

    if(start){

    range = range + nums[i];

    start = false;

    }

    else {

    range = new Integer(nums[i]).toString();

    }

    ret.add(range);

    }

    }

    return ret;

    }

    }

  7. public List summaryRanges(int[] nums) {

    List r = new LinkedList();

    if (nums == null) return r;
    for (int start = 0, i = 0; i ” + nums[i]);
    }
    start = i + 1;
    }
    }
    return r;
    }

  8. public class Solution {

    public List summaryRanges(int[] nums) {

    List result = new ArrayList();

    if(nums.length == 0) return result;

    if(nums.length == 1) {

    result.add(nums[0]+””);

    return result;

    }

    int beginVal = nums[0];

    for(int i=1; i beginVal) result.add(beginVal+”->”+nums[i-1]);

    if(nums[i-1] == beginVal) result.add(beginVal+””);

    beginVal = nums[i];

    }

    if(i==nums.length-1) {

    if(nums[i]-nums[i-1] != 1) result.add(beginVal+””);

    if(nums[i]-nums[i-1] == 1) result.add(beginVal+”->”+nums[i]);

    }

    }

    return result;

    }

    }


  9. public List summaryRanges(int[] nums) {
    List result = new ArrayList();
    int left = 0;
    int right = 0;
    while(right"+ nums[right]+"]");
    }else{
    result.add("["+nums[left]+"]");
    }
    left = right+1;
    }
    right++;
    }
    return result;
    }

Leave a Comment