DEV Community

Debesh P.
Debesh P.

Posted on

228. Summary Ranges | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/summary-ranges/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/summary-ranges/solutions/7510743/most-optimal-solution-beats-200-on-o1-in-5huw


leetcode 228


Solution

class Solution {
    public List<String> summaryRanges(int[] nums) {

        List<String> res = new ArrayList<>();
        int n = nums.length;

        for (int i = 0; i < n; i++) {
            int start = nums[i];

            while (i + 1 < n && nums[i + 1] - nums[i] == 1) {
                i++;
            }

            if (start == nums[i]) {
                res.add(String.valueOf(start));
            } else {
                res.add(start + "->" + nums[i]);
            }
        }

        return res;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)