Similar Problems
Similar Problems not available
Missing Ranges - Leetcode Solution
LeetCode: Missing Ranges Leetcode Solution
Difficulty: Easy
Topics: array
The Missing Ranges problem on LeetCode is a problem where we are given a sorted list of unique integers and a range containing the minimum and maximum value. We have to find the list of missing ranges in the given range.
For example, if we are given the input [0, 1, 3, 50, 75] and the range [0, 99], the output should be ["2", "4->49", "51->74", "76->99"].
To solve the problem, we need to iterate through the given list and find the missing ranges within the given range. We can do this by keeping track of the previous number and the current number and checking if the difference between them is greater than 1. If it is, we can add the missing range to a list.
Here is the step-by-step approach to solve the problem:
- Initialize a list to store the missing ranges.
- Iterate through the given list starting from the first element.
- If the current element is within the given range, check if it is adjacent to the previous element or not. If it is not adjacent, add the missing range to the list.
- After iterating through all elements, if the last element is within the given range, check if it is adjacent to the range's maximum value or not. If it is not adjacent, add the missing range to the list.
- Return the list of missing ranges.
Here is the solution to the problem:
def findMissingRanges(nums, lower, upper): missingRanges = [] prev = lower - 1
for i in range(len(nums)+1):
curr = upper + 1 if i == len(nums) else nums[i]
if prev+1 <= curr-1:
missingRanges.append(getRange(prev+1, curr-1))
prev = curr
return missingRanges
def getRange(num1, num2): return str(num1) if num1 == num2 else str(num1) + "->" + str(num2)
The findMissingRanges function takes three arguments, the list of nums, the lower bound, and the upper bound of the range. We initialize the missingRanges list and prev variable with lower - 1 to check the missing ranges between lower bound and the first element.
We iterate through the nums list, and if any element is missing, we add the missing range to the missingRanges list using the getRange function.
Finally, we return missingRanges, which contains all the missing ranges between lower bound and upper bound.
This solution has a time and space complexity of O(n), where n is the number of elements in the given list nums.
Missing Ranges Solution Code
1