Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit fbcdf23

Browse files
author
Ram swaroop
committed
consecutive elements : comments added
1 parent 6046746 commit fbcdf23

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

src/me/ramswaroop/arrays/ConsecutiveElements.java

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,31 @@
1010
public class ConsecutiveElements {
1111

1212
/**
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+
*
1430
* @param a
1531
* @return
1632
*/
1733
public static boolean areConsecutiveElements(int[] a) {
1834
int min = a[0], max = a[0];
1935
int[] visitedArray = new int[a.length];
2036

37+
// find min and max element
2138
for (int i = 1; i < a.length; i++) {
2239
if (a[i] < min) {
2340
min = a[i];
@@ -27,10 +44,12 @@ public static boolean areConsecutiveElements(int[] a) {
2744
}
2845
}
2946

47+
// diff of max and min should be equal to length of array
3048
if (a.length != max - min + 1) {
3149
return false;
3250
}
3351

52+
// check for distinct elements
3453
for (int i = 0; i < a.length; i++) {
3554
if (visitedArray[a[i] - min] == 0) {
3655
visitedArray[a[i] - min] = a[i];

0 commit comments

Comments
 (0)