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

Commit 0379082

Browse files
author
Ram swaroop
committed
consecutive elements : added another method which uses O(1) auxiliary space
1 parent fbcdf23 commit 0379082

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

src/me/ramswaroop/arrays/ConsecutiveElements.java

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ public class ConsecutiveElements {
2525
* 2) All elements are distinct.
2626
* <p/>
2727
* 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.
2929
*
3030
* @param a
3131
* @return
@@ -61,10 +61,53 @@ public static boolean areConsecutiveElements(int[] a) {
6161
return true;
6262
}
6363

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+
64102
public static void main(String a[]) {
65103
System.out.println(areConsecutiveElements(new int[]{5, 4, 3, 2, 1}));
66104
System.out.println(areConsecutiveElements(new int[]{67, 68, 69, 72, 70, 71}));
67105
System.out.println(areConsecutiveElements(new int[]{67, 68, 69, 72, 70, 71, 70}));
68106
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}));
69112
}
70113
}

0 commit comments

Comments
 (0)