Monday, October 26, 2020

Summary Ranges

Problem: You are given a sorted unique integer array. Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of input array is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in input array.

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

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

Example:

Input: nums = [3,4,5,9,12,13]
Output: ["3->5","9","12->13"]
Explanation: The ranges are:
[3, 5] --> "3->5"
[9, 9] --> "9"
[12, 13] --> "12->13"


Approach: Not much to discuss here. Its a straight forward problem. You can easily understand the solution by looking at the code.


Implementation in C#:

        public static IList<string> SummaryRanges(int[] nums)

        {

            List<string> result = new List<string>();

            if (nums?.Length == 0)

            {

                return result;

            }

            string currRange = nums[0].ToString();

            for (int i = 1; i < nums.Length; ++i)

            {

                if (nums[i] > nums[i - 1] + 1)

                {

                    if (int.Parse(currRange) != nums[i - 1])

                    {

                        currRange += $"->{nums[i - 1]}";

                    }

                    result.Add(currRange);

                    currRange = nums[i].ToString();

                }

            }

            if (int.Parse(currRange) != nums[nums.Length - 1])

            {

                currRange += $"->{nums[nums.Length - 1]}";

            }

            result.Add(currRange);           

            return result;

        }


Complexity: O(n)

No comments:

Post a Comment