Skip to content

Commit 8a98d0b

Browse files
Tushar RoyTushar Roy
authored andcommitted
Summary range
1 parent ef7d6a7 commit 8a98d0b

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.interview.array;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
import java.util.List;
6+
7+
/**
8+
* Date 10/19/2016
9+
* @author Tushar Roy
10+
*
11+
* Given a sorted integer array without duplicates, return the summary of its ranges.
12+
* For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
13+
*
14+
* Solution -
15+
* Just check if num[i] + 1 != num[i + 1]. If its not equal means you need to add previous range to result
16+
* and start a new range.
17+
*
18+
* Time complexity O(n)
19+
*
20+
* https://leetcode.com/problems/summary-ranges/
21+
*/
22+
public class SummaryRanges {
23+
public List<String> summaryRanges(int[] nums) {
24+
if (nums.length == 0) {
25+
return Collections.EMPTY_LIST;
26+
}
27+
if (nums.length == 1) {
28+
return Collections.singletonList(String.valueOf(nums[0]));
29+
}
30+
int start = 0;
31+
List<String> result = new ArrayList<>();
32+
for (int i = 0; i < nums.length - 1; i++) {
33+
if ((nums[i] + 1) != nums[i + 1]) {
34+
result.add(makeRange(nums[start], nums[i]));
35+
start = i + 1;
36+
}
37+
}
38+
if ((nums[nums.length - 2] + 1) != nums[nums.length - 1]) {
39+
start = nums.length - 1;
40+
}
41+
result.add(makeRange(nums[start], nums[nums.length - 1]));
42+
return result;
43+
}
44+
45+
private String makeRange(int a, int b) {
46+
if (a == b) {
47+
return String.valueOf(a);
48+
}
49+
return a + "->" + b;
50+
}
51+
}

0 commit comments

Comments
 (0)