-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |