10
10
public class ConsecutiveElements {
11
11
12
12
/**
13
- *
13
+ * Given an unsorted array of numbers, write a function that returns true if array consists of consecutive numbers.
14
+ * <p/>
15
+ * Examples:
16
+ * a) If array is {5, 2, 3, 1, 4}, then the function should return true because the array has consecutive numbers
17
+ * from 1 to 5.
18
+ * b) If array is {34, 23, 52, 12, 3 }, then the function should return false because the elements are not consecutive.
19
+ * c) If the array is {7, 6, 5, 5, 3, 4}, then the function should return false because 5 and 5 are not consecutive.
20
+ * <p/>
21
+ * ALGORITHM:
22
+ * The idea is to check for following two conditions. If following two conditions are true, then return true.
23
+ * 1) max – min + 1 = n where max is the maximum element in array, min is minimum element in array and n is the number
24
+ * of elements in array.
25
+ * 2) All elements are distinct.
26
+ * <p/>
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[].
29
+ *
14
30
* @param a
15
31
* @return
16
32
*/
17
33
public static boolean areConsecutiveElements (int [] a ) {
18
34
int min = a [0 ], max = a [0 ];
19
35
int [] visitedArray = new int [a .length ];
20
36
37
+ // find min and max element
21
38
for (int i = 1 ; i < a .length ; i ++) {
22
39
if (a [i ] < min ) {
23
40
min = a [i ];
@@ -27,10 +44,12 @@ public static boolean areConsecutiveElements(int[] a) {
27
44
}
28
45
}
29
46
47
+ // diff of max and min should be equal to length of array
30
48
if (a .length != max - min + 1 ) {
31
49
return false ;
32
50
}
33
51
52
+ // check for distinct elements
34
53
for (int i = 0 ; i < a .length ; i ++) {
35
54
if (visitedArray [a [i ] - min ] == 0 ) {
36
55
visitedArray [a [i ] - min ] = a [i ];
0 commit comments