@@ -25,7 +25,7 @@ public class ConsecutiveElements {
25
25
* 2) All elements are distinct.
26
26
* <p/>
27
27
* To check if all elements are distinct, we can create a visited[] array of size n. We can map the ith element of input
28
- * array arr[] to visited array by using arr[i] – min as index in visited[].
28
+ * array arr[] to visited array by using arr[i] – min as index in visited[]. So we need O(n) auxiliary space.
29
29
*
30
30
* @param a
31
31
* @return
@@ -61,10 +61,53 @@ public static boolean areConsecutiveElements(int[] a) {
61
61
return true ;
62
62
}
63
63
64
+ /**
65
+ * This approach is similar to {@link me.ramswaroop.arrays.ConsecutiveElements#areConsecutiveElements(int[])} but
66
+ * requires O(1) auxiliary space instead of O(n). But the only con of this method is that it modifies the original
67
+ * input array {@param a}.
68
+ *
69
+ * @param a
70
+ * @return
71
+ */
72
+ public static boolean areConsecutiveElementsInO1Space (int [] a ) {
73
+ int min = a [0 ], max = a [0 ];
74
+
75
+ // find min and max element
76
+ for (int i = 1 ; i < a .length ; i ++) {
77
+ if (a [i ] < min ) {
78
+ min = a [i ];
79
+ }
80
+ if (a [i ] > max ) {
81
+ max = a [i ];
82
+ }
83
+ }
84
+
85
+ // diff of max and min should be equal to length of array
86
+ if (a .length != max - min + 1 ) {
87
+ return false ;
88
+ }
89
+
90
+ // check for distinct elements
91
+ for (int i = 0 ; i < a .length ; i ++) {
92
+ if (a [Math .abs (a [i ]) - min ] >= 0 ) {
93
+ a [Math .abs (a [i ]) - min ] = -(a [Math .abs (a [i ]) - min ]);
94
+ } else {
95
+ return false ;
96
+ }
97
+ }
98
+
99
+ return true ;
100
+ }
101
+
64
102
public static void main (String a []) {
65
103
System .out .println (areConsecutiveElements (new int []{5 , 4 , 3 , 2 , 1 }));
66
104
System .out .println (areConsecutiveElements (new int []{67 , 68 , 69 , 72 , 70 , 71 }));
67
105
System .out .println (areConsecutiveElements (new int []{67 , 68 , 69 , 72 , 70 , 71 , 70 }));
68
106
System .out .println (areConsecutiveElements (new int []{8 , 5 , 2 , 4 , 3 , 1 }));
107
+ System .out .println ("==============" );
108
+ System .out .println (areConsecutiveElementsInO1Space (new int []{5 , 4 , 3 , 2 , 1 }));
109
+ System .out .println (areConsecutiveElementsInO1Space (new int []{67 , 68 , 69 , 72 , 70 , 71 }));
110
+ System .out .println (areConsecutiveElementsInO1Space (new int []{67 , 68 , 69 , 72 , 70 , 71 , 70 }));
111
+ System .out .println (areConsecutiveElementsInO1Space (new int []{8 , 5 , 2 , 4 , 3 , 1 }));
69
112
}
70
113
}
0 commit comments