Logo
    Akhil Abraham
    Akhil Abraham
    0228 - Summary Ranges
    0228 - Summary Ranges

    0228 - Summary Ranges

    Difficulty
    Easy
    Language
    Python
    URL
    https://leetcode.com/problems/summary-ranges/

    Solution 1 - Two Pointer Iteration

    Iterate through the sorted array, tracking the start of each consecutive range. When the next element is not consecutive (or we reach the end), form the range string and add it to the result.

    TimeComplexity:O(n)TimeComplexity: O(n)TimeComplexity:O(n)
    SpaceComplexity:O(1)SpaceComplexity: O(1)SpaceComplexity:O(1)

    Solution 2 - Using enumerate() with Range Tracking

    Uses enumerate() to iterate and detects range boundaries by comparing each element to its expected value based on the starting element of the current range.

    TimeComplexity:O(n)TimeComplexity: O(n)TimeComplexity:O(n)
    SpaceComplexity:O(1)SpaceComplexity: O(1)SpaceComplexity:O(1)
    Logo

    ©️ 2020-2026, Akhil Abraham.

    LinkedInGitHubMediumX
    """ 0228.1 - Solution 1 - Two Pointer Iteration """
    
    #####################################################################################
    # Imports
    #####################################################################################
    from typing import List
    
    #####################################################################################
    # Classes
    #####################################################################################
    class Solution:
        """Solution Class"""
    
        def summaryRanges(self, nums: List[int]) -> List[str]:
            """Summary Ranges Function"""
            result = []
            i = 0
            n = len(nums)
    
            while i < n:
                start = nums[i]
                while i + 1 < n and nums[i + 1] == nums[i] + 1:
                    i += 1
                if nums[i] == start:
                    result.append(str(start))
                else:
                    result.append(f"{start}->{nums[i]}")
                i += 1
    
            return result
    
    
    #####################################################################################
    # Functions
    #####################################################################################
    def testcase():
        """Test Function"""
        print(Solution().summaryRanges([0, 1, 2, 4, 5, 7]))
        # Expected: ["0->2", "4->5", "7"]
        print(Solution().summaryRanges([0, 2, 3, 4, 6, 8, 9]))
        # Expected: ["0", "2->4", "6", "8->9"]
        print(Solution().summaryRanges([]))
        # Expected: []
    
    
    #####################################################################################
    # Main
    #####################################################################################
    if __name__ == "__main__":
        testcase()
    
    """ 0228.2 - Solution 2 - Using Enumerate with Range Tracking """
    
    #####################################################################################
    # Imports
    #####################################################################################
    from typing import List
    
    #####################################################################################
    # Classes
    #####################################################################################
    class Solution:
        """Solution Class"""
    
        def summaryRanges(self, nums: List[int]) -> List[str]:
            """Summary Ranges Function"""
            if not nums:
                return []
    
            result = []
            start = 0
    
            for idx, num in enumerate(nums):
                # Check if this is the last element or next is not consecutive
                if idx == len(nums) - 1 or nums[idx + 1] != num + 1:
                    if start == idx:
                        result.append(str(nums[start]))
                    else:
                        result.append(f"{nums[start]}->{nums[idx]}")
                    start = idx + 1
    
            return result
    
    
    #####################################################################################
    # Functions
    #####################################################################################
    def testcase():
        """Test Function"""
        print(Solution().summaryRanges([0, 1, 2, 4, 5, 7]))
        # Expected: ["0->2", "4->5", "7"]
        print(Solution().summaryRanges([0, 2, 3, 4, 6, 8, 9]))
        # Expected: ["0", "2->4", "6", "8->9"]
        print(Solution().summaryRanges([]))
        # Expected: []
    
    
    #####################################################################################
    # Main
    #####################################################################################
    if __name__ == "__main__":
        testcase()