DEV Community

codingpineapple
codingpineapple

Posted on

2 1

Leetcode 163. Missing Ranges (javascript solution)

Description:

You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are in the inclusive range.

A number x is considered missing if x is in the range [lower, upper] and x is not in nums.

Return the smallest sorted list of ranges that cover every missing number exactly. That is, no element of nums is in any of the ranges, and each missing number is in one of the ranges.

Each range [a,b] in the list should be output as:

"a->b" if a != b
"a" if a == b

Solution:

Time Complexity : O(n)
Space Complexity: O(1)

var findMissingRanges = function(nums, lower, upper) {
    // array to add ranges
    const result = []
    // start at lower - 1 for edge case where lower === nums[0]
    let prev = lower - 1;
    // loop for nums.length times so we can compare the last value with upper
    for (let i = 0; i <= nums.length; i++) {
        // current number to compare to prev
        // when i === nums.length we will compare prev = nums[nums.length-1] and upper
        // the upper+1 is to account for nums[nums.length-1]===upper
        let curr = (i < nums.length) ? nums[i] : upper + 1;
        // check if we need to add a range to the array
        if (prev + 1 <= curr - 1) {
            // if equal then add any of the numbers to the array
            // if < than, then add the range string to the array
            result.push(prev + 1===curr - 1?`${prev + 1}`:`${prev + 1}->${curr - 1}`);
        }
        // set prev to compare in the next iteration
        prev = curr;
    }
    return result 
};
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay