Similar Problems

Similar Problems not available

Find The Start And End Number Of Continuous Ranges - Leetcode Solution

Companies:

LeetCode:  Find The Start And End Number Of Continuous Ranges Leetcode Solution

Difficulty: Medium

Topics: database  

Problem:

Given a sorted array of integers, find the start and end number of continuous ranges in the array.

Example:

Input: [1,2,3,5,7,8,10] Output: [[1,3],[5,5],[7,8],[10,10]]

Solution:

Approach:

The problem can be solved by using two pointer approach. The two pointers, start and end, will initially point to the first element of the array. The end pointer will be moved until the next element is not consecutive to the current element. At this point, we have found a range from start to end of consecutive numbers. We add the start and end pointers to the list of the ranges and move the start pointer to the next element. We continue to move the end pointer until the next element is not consecutive to the current element and we repeat the previous steps until the end of the array is reached.

Algorithm:

  1. Create an empty list to store the ranges.
  2. Create start and end pointers, initialized to the first element of the array.
  3. Loop through the array from index 1 to n-1: a. If the current element is consecutive to the previous element, move the end pointer to the current element. b. If the current element is not consecutive to the previous element, add the range [start, end] to the list and move the start pointer to the current element.
  4. Add the last range [start, end] to the list.
  5. Return the list of ranges.

Implementation:

def findContinuousRanges(nums):
    # create an empty list to store the ranges
    ranges = []
    # initialize the start and end pointers
    start, end = nums[0], nums[0]
    # loop through the array from index 1 to n-1
    for i in range(1, len(nums)):
        # if the current element is consecutive to the previous element, move the end pointer to the current element
        if nums[i] == end + 1:
            end = nums[i]
        # if the current element is not consecutive to the previous element, add the range [start, end] to the list and move the start pointer to the current element
        else:
            ranges.append([start, end])
            start, end = nums[i], nums[i]
    # add the last range [start, end] to the list
    ranges.append([start, end])
    # return the list of ranges
    return ranges

Test Cases:

Input: [1,2,3,5,7,8,10] Output: [[1,3],[5,5],[7,8],[10,10]]

Input: [1,3,4,5,8,9,10] Output: [[1,1],[3,5],[8,10]]

Input: [1,2,3,4,5] Output: [[1, 5]]

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

Find The Start And End Number Of Continuous Ranges Solution Code

1