Skip to content

Commit ad78f1a

Browse files
Merge pull request #3144 from benmak11/1630
Create 1630-arithmetic-subarrays.java
2 parents 30a663d + 744dee8 commit ad78f1a

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

java/1630-arithmetic-subarrays.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,5 +16,43 @@ public List<Boolean> checkArithmeticSubarrays(int[] nums, int[] l, int[] r) {
1616
res.add(isArithmatic);
1717
}
1818
return res;
19+
}
20+
21+
/*
22+
******************************************************
23+
****************** SECOND SOLUTION *******************
24+
******************************************************
25+
*/
26+
27+
/**
28+
* Runtime Complexity: O(n * m)
29+
* Space Complexity: O(n)
30+
*/
31+
public List<Boolean> checkArithmeticSubarrays(int[] nums, int[] l, int[] r) {
32+
List<Boolean> res = new ArrayList<>();
33+
34+
for (int i = 0; i < l.length; i++) {
35+
res.add(check(nums, l[i], r[i]));
36+
}
37+
38+
return res;
39+
}
40+
41+
private boolean check(int[] nums, int l, int r) {
42+
List<Integer> subArray = new ArrayList<>();
43+
for (int i = l; i < r + 1; i++) {
44+
subArray.add(nums[i]);
45+
}
46+
Collections.sort(subArray);
47+
48+
Set<Integer> diffTrack = new HashSet<>();
49+
diffTrack.add(Math.abs(subArray.get(0) - subArray.get(1)));
50+
51+
for (int i = 2; i < subArray.size(); i++) {
52+
int diff = Math.abs(subArray.get(i) - subArray.get(i - 1));
53+
if (!diffTrack.contains(diff))
54+
return false;
55+
}
56+
return true;
1957
}
2058
}

0 commit comments

Comments
 (0)