Sobes.tech
Senior

Input: nums = [0,1,2,4,5,7] Output: ["0->2","4->5","7"] public class DemoApplication { public static void main(String[] args) { int[] nums = {0,1,2,4,6,5,7,10}; System.out.println(summary(nums)); } public static List<String> summary(int[] nums){ List<String> result = new ArrayList<>(); int i = 0; int n = nums.length; while (i < n) { int start = nums[i]; while (i + 1 < n && nums[i+1] == nums[i] + 1){ i++; } int end = nums[i]; if (start == end){ result.add(String.valueOf(start)); } else { result.add(start + "->" + end); } i++; } return result; } }

sobes.tech AI

Answer from AI

The provided code has a problem: the array nums is not sorted, and the algorithm assumes that the input data is sorted for correct identification of consecutive ranges.

To fix this, you need to sort the array before processing:

import java.util.*;

public class DemoApplication {

    public static void main(String[] args) {
        int[] nums = {0,1,2,4,6,5,7,10};
        Arrays.sort(nums); // sort the array
        System.out.println(summary(nums));
    }

    public static List<String> summary(int[] nums){
        List<String> result = new ArrayList<>();
        int i = 0;
        int n = nums.length;

        while (i < n) {
            int start = nums[i];
            while (i + 1 < n && nums[i+1] == nums[i] + 1){
                i++;
            }
            int end = nums[i];
            if (start == end){
                result.add(String.valueOf(start));
            } else {
                result.add(start + "->" + end);
            }
            i++;
        }
        return result;
    }
}

After sorting, the code correctly merges consecutive numbers into ranges, for example, [0,1,2,4,5,6,7,10] becomes ["0->2", "4->7", "10"].