-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
59 lines (44 loc) · 1.52 KB
/
Solution.java
File metadata and controls
59 lines (44 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package array.apmiss;
import java.util.List;
/**
* Arithmetic Progression Missing Element Finder
*/
public class Solution {
public int findMissing(List<Integer> sequence) {
int step = findStep(sequence);
// perform a binary search for missing element in O(log(n))
int start = 0;
int end = sequence.size() - 1;
boolean foundMissing = false;
int missing = -1;
while (start <= end) {
int middle = start + (end - start) / 2;
int expected = sequence.get(0) + step * middle;
if (expected == sequence.get(middle)) {
start = middle + 1;
} else {
end = middle - 1;
// found a candidate for missing element, however must continue
// binary search all the way to make sure it is the right one
foundMissing = true;
missing = expected;
}
}
if (foundMissing) {
return missing;
} else {
// all elements in sequence were valid, assume missing must be at end of sequence
return sequence.get(0) + step * sequence.size();
}
}
public static int findStep(List<Integer> sequence) {
int first = sequence.get(0);
int second = sequence.get(1);
int third = sequence.get(2);
int step = Math.min(Math.abs(second - first), Math.abs(third - second));
if (second - first < 0) {
step *= -1;
}
return step;
}
}