| | | 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.ArithmeticSubarrays; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class ArithmeticSubarraysHashSet : IArithmeticSubarrays |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(m * n) |
| | | 19 | | /// Space complexity - O(n) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="nums"></param> |
| | | 22 | | /// <param name="l"></param> |
| | | 23 | | /// <param name="r"></param> |
| | | 24 | | /// <returns></returns> |
| | | 25 | | public IList<bool> CheckArithmeticSubarrays(int[] nums, int[] l, int[] r) |
| | 6 | 26 | | { |
| | 6 | 27 | | var result = new bool[l.Length]; |
| | | 28 | | |
| | 48 | 29 | | for (var i = 0; i < l.Length; i++) |
| | 18 | 30 | | { |
| | 36 | 31 | | int start = l[i], end = r[i]; |
| | 36 | 32 | | int minVal = int.MaxValue, maxVal = int.MinValue; |
| | 18 | 33 | | var elements = new HashSet<int>(); |
| | | 34 | | |
| | 156 | 35 | | for (var j = start; j <= end; j++) |
| | 60 | 36 | | { |
| | 60 | 37 | | minVal = Math.Min(minVal, nums[j]); |
| | 60 | 38 | | maxVal = Math.Max(maxVal, nums[j]); |
| | 60 | 39 | | elements.Add(nums[j]); |
| | 60 | 40 | | } |
| | | 41 | | |
| | 18 | 42 | | var subArrayLength = end - start + 1; |
| | | 43 | | |
| | 18 | 44 | | if (subArrayLength < 2 || (maxVal - minVal) % (subArrayLength - 1) != 0) |
| | 4 | 45 | | { |
| | 4 | 46 | | result[i] = false; |
| | | 47 | | |
| | 4 | 48 | | continue; |
| | | 49 | | } |
| | | 50 | | |
| | 14 | 51 | | var diff = (maxVal - minVal) / (subArrayLength - 1); |
| | 14 | 52 | | var isArithmetic = true; |
| | | 53 | | |
| | 106 | 54 | | for (var j = 0; j < subArrayLength; j++) |
| | 41 | 55 | | { |
| | 41 | 56 | | if (elements.Contains(minVal + (j * diff))) |
| | 39 | 57 | | { |
| | 39 | 58 | | continue; |
| | | 59 | | } |
| | | 60 | | |
| | 2 | 61 | | isArithmetic = false; |
| | | 62 | | |
| | 2 | 63 | | break; |
| | | 64 | | } |
| | | 65 | | |
| | 14 | 66 | | result[i] = isArithmetic; |
| | 14 | 67 | | } |
| | | 68 | | |
| | 6 | 69 | | return result; |
| | 6 | 70 | | } |
| | | 71 | | } |