Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Summary ranges challenge

Sharing is caring!

Problem statement
Given a sorted integer array without duplicates, return the summary of its ranges for consecutive numbers.

For example, given [0,1,2,4,5,7], return [0\rightarrow 2,4\rightarrow 5,7].

Solution

public class SummaryRanges {
    private static String summary(int[] a) {
        String ans = "";

        int start = a[0];
        ans = ans + start;
        for (int i = 1; i < a.length; i++) {
            if (a[i - 1] != a[i] - 1) {
                if (a[i - 1] != start) {
                    ans = ans + "->" + a[i - 1];
                }
                start = a[i];
                ans = ans + ", " + start;
            }
        }

        return ans;
    }

    public static void main(String[] args) {
        int[] a = { 0, 1, 2, 4, 5, 7, 9 };
        System.out.println(summary(a));
    }
}