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) {

summary.add(Integer.toString(nums[0]));

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]);

summary.add(str);

}

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

else {

summary.add(Integer.toString(nums[startRange]));

}

// **** ****

startRange = i;

}

}

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

if (startRange != -1) {

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

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

summary.add(Integer.toString(nums[startRange]));

}

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

else {

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

str += “->”;

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

summary.add(str);

}

}

// **** ****

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

Follow me on Twitter:  @john_canessa

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.