Skip to content

Commit

Permalink
Add Q1630 solution
Browse files Browse the repository at this point in the history
  • Loading branch information
ungtsuhan committed Nov 23, 2023
1 parent 8b31de8 commit 7270ae2
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
18 changes: 18 additions & 0 deletions LeetCode.Tests/Q1630_ArithmetricSubarraysTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
namespace LeetCode.Tests;

public class Q1630Tests
{
[Theory]
[InlineData(new int[] { 4, 6, 5, 9, 3, 7 }, new int[] { 0, 0, 2 }, new int[] { 2, 3, 5 }, new bool[] { true, false, true })]
[InlineData(new int[] { -12, -9, -3, -12, -6, 15, 20, -25, -20, -15, -10 }, new int[] { 0, 1, 6, 4, 8, 7 }, new int[] { 4, 4, 9, 7, 9, 10 }, new bool[] { false, true, false, false, true, true })]
public void CheckArithmeticSubarrays_ValidInput_ReturnsCorrectResult(int[] nums, int[] l, int[] r, bool[] expectedResult)
{
// Arrange

// Act
var actualResult = Q1630.CheckArithmeticSubarrays(nums, l, r);

// Assert
Assert.Equal(expectedResult, [.. actualResult]);
}
}
41 changes: 41 additions & 0 deletions LeetCode/Q1630_ArithmetricSubarrays.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
namespace LeetCode;

public class Q1630
{
// Time Complexity: O(n * m)
// Space Complexity: O(n)

public static IList<bool> CheckArithmeticSubarrays(int[] nums, int[] l, int[] r)
{
List<bool> result = [];
for (var i = 0; i < l.Length; i++) // O(n * m)
{
var subArray = ExtractSubArray(nums, l[i], r[i]); // O(m)
result.Add(IsArithmetric(subArray)); // O(m)
}
return result;
}

private static List<int> ExtractSubArray(int[] nums, int l, int r) // O(m)
{
List<int> subArray = new(r - l + 1);
for (var p = l; p <= r; p++)
subArray.Add(nums[p]);
return subArray;
}

private static bool IsArithmetric(List<int> arr) // O (m)
{
if (arr.Count == 1)
return true;

var sortedArr = arr.OrderBy(x => x).ToList(); // O(m log m)
var commonDifference = sortedArr[1] - sortedArr[0];
for (var i = 2; i < sortedArr.Count; i++) // O (m)
{
if (sortedArr[i] - sortedArr[i - 1] != commonDifference)
return false;
}
return true;
}
}

0 comments on commit 7270ae2

Please sign in to comment.