compose Ranges from given numbers

compose Ranges from given numbers

Problem Statement: Given a sorted integer array that does not contain any duplicates, return a summary of the number ranges it contains.

Example

For nums = [-1, 0, 1, 2, 6, 7, 9], the output should be
solution(nums) = ["-1->2", "6->7", "9"].

String[] solution(int[] nums) {

    // As we do not know how many ranges will be there, we have taken a list
    List<String> list = new ArrayList<>();
    int n = nums.length;

    for(int i=0; i<n; i++) {
        int temp = nums[i];
        String str = Integer.toString(temp);
        //keep moving forward if the numbers are in order
        while(i+1<n && nums[i+1]==nums[i]+1) {
            i++;
        }
        // check if we are not at the first number only (Ex- "9" is alone)
        if(temp!=nums[i]) {
            str = str + "->";
            str = str + Integer.toString(nums[i]);
        }
        // Add the string to the list
        list.add(str);        
    }
    // convert the list to the array
    String[] ans = new String[list.size()];
    for(int i=0; i<list.size(); i++) {
        ans[i] = list.get(i);
    }
    return ans;

}

Time complexity - O(n), space complexity - O(n)