| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | | 3 | | // All Rights Reserved. |
| | | 4 | | // -------------------------------------------------------------------------------- |
| | | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | | 9 | | // known as Yevhenii Yeriemeieiv). |
| | | 10 | | // -------------------------------------------------------------------------------- |
| | | 11 | | |
| | | 12 | | namespace LeetCode.Algorithms.SummaryRanges; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class SummaryRangesIterative : ISummaryRanges |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n) |
| | | 19 | | /// Space complexity - O(n) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="nums"></param> |
| | | 22 | | /// <returns></returns> |
| | | 23 | | public IList<string> SummaryRanges(int[] nums) |
| | 2 | 24 | | { |
| | 2 | 25 | | if (nums.Length == 0) |
| | 0 | 26 | | { |
| | 0 | 27 | | return new List<string>(); |
| | | 28 | | } |
| | | 29 | | |
| | 2 | 30 | | var ranges = new List<string>(); |
| | | 31 | | |
| | 2 | 32 | | var start = nums[0]; |
| | 2 | 33 | | var end = start; |
| | | 34 | | |
| | 26 | 35 | | for (var i = 1; i < nums.Length; i++) |
| | 11 | 36 | | { |
| | 11 | 37 | | if (end + 1 == nums[i]) |
| | 6 | 38 | | { |
| | 6 | 39 | | end = nums[i]; |
| | 6 | 40 | | } |
| | | 41 | | else |
| | 5 | 42 | | { |
| | 5 | 43 | | ranges.Add(GetRangeString(start, end)); |
| | | 44 | | |
| | 5 | 45 | | start = nums[i]; |
| | 5 | 46 | | end = start; |
| | 5 | 47 | | } |
| | 11 | 48 | | } |
| | | 49 | | |
| | 2 | 50 | | ranges.Add(GetRangeString(start, end)); |
| | | 51 | | |
| | 2 | 52 | | return ranges; |
| | 2 | 53 | | } |
| | | 54 | | |
| | | 55 | | private static string GetRangeString(int start, int end) |
| | 7 | 56 | | { |
| | 7 | 57 | | return start == end ? start.ToString() : $"{start}->{end}"; |
| | 7 | 58 | | } |
| | | 59 | | } |