This website contains ALL LeetCode **Premium** problems for
**FREE!!**.

All leaked interview problems are collected from Internet.

All leaked interview problems are collected from Internet.

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

**Example 1:**

Input:[0,1,2,4,5,7]Output:["0->2","4->5","7"]

**Example 2:**

Input:[0,2,3,4,6,8,9]Output:["0","2->4","6","8->9"]

**Credits:**

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

b'

\n## Solution

\n\n\n

'
**Intuition**

A range covers consecutive elements. If two adjacent elements have difference larger than , the two elements does not belong to the same range.

\n**Algorithm**

To summarize the ranges, we need to know how to separate them. The array is sorted and without duplicates. In such array, two adjacent elements have difference either 1 or larger than 1. If the difference is 1, they should be put in the same range; otherwise, separate ranges.

\nWe also need to know the start index of a range so that we can put it in the result list. Thus, we keep two indices, representing the two boundaries of current range. For each new element, we check if it extends the current range. If not, we put the current range into the list.

\nDon\'t forget to put the last range into the list. One can do this by either a special condition in the loop or putting the last range in to the list after the loop.

\n**Java**

public class Solution {\n public List<String> summaryRanges(int[] nums) {\n List<String> summary = new ArrayList<>();\n for (int i = 0, j = 0; j < nums.length; ++j) {\n // check if j + 1 extends the range [nums[i], nums[j]]\n if (j + 1 < nums.length && nums[j + 1] == nums[j] + 1)\n continue;\n // put the range [nums[i], nums[j]] into the list\n if (i == j)\n summary.add(nums[i] + "");\n else\n summary.add(nums[i] + "->" + nums[j]);\n i = j + 1;\n }\n return summary;\n }\n}\n

**Java (Alternative)**

public class Solution {\n public List<String> summaryRanges(int[] nums) {\n List<String> summary = new ArrayList<>();\n for (int i, j = 0; j < nums.length; ++j){\n i = j;\n // try to extend the range [nums[i], nums[j]]\n while (j + 1 < nums.length && nums[j + 1] == nums[j] + 1)\n ++j;\n // put the range into the list\n if (i == j)\n summary.add(nums[i] + "");\n else\n summary.add(nums[i] + "->" + nums[j]);\n }\n return summary;\n }\n}\n

**Complexity Analysis**

- \n
- \n
Time complexity : . Each element is visited constant times: either in comparison with neighbor or put in the result list.

\n \n - \n
Space complexity : . All the auxiliary space we need is the two indices, if we don\'t count the return list.

\n \n