1
+ /**
2
+ * Problem Name : Arithmetic Subarrays
3
+ * Concept Involved : Maths, Interval Count, Array
4
+ *
5
+ * Execution Time : 500 ms
6
+ * Memory Consumed : 40.6 mb
7
+ *
8
+ * Solution : We have been asked Q queries. Every query has a range l and r
9
+ * and we have to tell whether the array elements from l to r form an
10
+ * Arithmetic Sequence.
11
+ * The idea is to find the maximum and minimum element of the sub array for
12
+ * every query and divide the difference of maximum and minimum element into
13
+ * (maximum-minimum)/x equal parts, where x is the size of the sub array.
14
+ * Now we jump to every part and check whether the given part is present in the
15
+ * sub array. For this we can use a hash set, I have used index based hashing
16
+ * in the array to save some time.
17
+ */
18
+
19
+ class Solution {
20
+ public int getValue (int ele ){
21
+ if (ele < 0 ){
22
+ return 100000 - ele ;
23
+ }
24
+ return ele ;
25
+ }
26
+ public List <Boolean > checkArithmeticSubarrays (int [] nums , int [] l , int [] r ) {
27
+ int m = l .length ;
28
+ ArrayList <Boolean > res = new ArrayList <>();
29
+
30
+ for (int i =0 ; i <m ; i ++){
31
+ int li = l [i ];
32
+ int ri = r [i ];
33
+
34
+ int maxel = Integer .MIN_VALUE ;
35
+ int minel = Integer .MAX_VALUE ;
36
+ int [] index = new int [200001 ];
37
+
38
+ for (int j =li ; j <=ri ; j ++){
39
+ maxel = Math .max (maxel , nums [j ]);
40
+ minel = Math .min (minel , nums [j ]);
41
+
42
+ int ele = (nums [j ] < 0 ) ? 100000 - nums [j ] : nums [j ];
43
+ index [ele ]++;
44
+ }
45
+
46
+ int diff = maxel - minel ;
47
+ int subs = ri -li ;
48
+
49
+ if (diff %subs == 0 ){
50
+ int jump = diff /subs ;
51
+ int start = minel ;
52
+ while ((start +jump ) <= maxel && index [getValue (start +jump )] == 1 ){
53
+ start += jump ;
54
+ }
55
+ if (start < maxel ){
56
+ res .add (false );
57
+ }
58
+ else {
59
+ res .add (true );
60
+ }
61
+ }
62
+ else {
63
+ res .add (false );
64
+ }
65
+ }
66
+
67
+ return res ;
68
+ }
69
+ }
0 commit comments