# Summary Ranges

This challenge from LeetCode may be found at the following URL:  https://leetcode.com/problems/summary-ranges/?tab=Description

If interested, following is a screen capture from my Eclipse IDE:

>>> N: 6 <== number of numbers that follows

0 1 2 4 5 7 <== sorted numbers

summary: [0->2, 4->5, 7]

In addition I tried the following custom test cases:

3

0 2 3

4

0 1 2 9

4

0 2 3 9

8

0 1 2 4 6 7 8 9

0

1

3

9

-12 -9 -8 -3 0 5 6 7 9

My test code in Java follows:

/**

* Test code

*/

public static void main(String[] args) {

// **** ****

Scanner sc = new Scanner(System.in);

// **** get number of entries for the array ****

System.out.print(“>>> N: “);

int N = sc.nextInt();

int[] nums = new int[N];

// **** populate array of numbers ****

for (int n = 0; n < N; n++) {

nums[n] = sc.nextInt();

}

// **** close scanner ****

sc.close();

// **** build list of numbers ****

List<String> summary = summaryRanges(nums);

System.out.print(“summary: ” + summary.toString());

}

The code for the solution follows:

/**

* Build list of ranges.

*/

static List<String> summaryRanges(int[] nums) {

List<String> summary = new ArrayList<String>();

// **** special case(s) ****

if (nums.length == 0) {

return summary;

}

if (nums.length == 1) {

return summary;

}

// **** traverse list of integers ****

int startRange = 0;

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

// **** close current range (if needed) ****

if (nums[i – 1] + 1 != nums[i]) {

// **** range of numbers ****

if (startRange + 1 != i) {

String str = Integer.toString(nums[startRange]);

str += “->”;

str += Integer.toString(nums[i – 1]);

}

// **** single number ****

else {

}

// **** ****

startRange = i;

}

}

// **** complete range (if needed) ****

if (startRange != -1) {

// **** single number ****

if (startRange == (nums.length – 1)) {

}

// **** range of numbers ****

else {

String str = Integer.toString(nums[startRange]);

str += “->”;

str += Integer.toString(nums[nums.length – 1]);

}

}

// **** ****

return summary;

}

If you have comments or questions regarding this or any other entry in this blog please do not hesitate and send me a message. If you want to suggest a different topic or issue please let me know. I will not use your name unless you explicitly allow me.

John

john.canessa@gmail