-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmallestLetterGreaterThanTarget.java
More file actions
34 lines (33 loc) · 1.21 KB
/
Copy pathSmallestLetterGreaterThanTarget.java
File metadata and controls
34 lines (33 loc) · 1.21 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
/**
* Find the next smallest letter greater than target
*
* Given a sorted array "letters", return the smallest
* character in the array that is larger than target.
*
* The letters wrap around, so that if the target is
* greater than all letters in the array return
* the first element of the array.
*/
public class SmallestLetterGreaterThanTarget {
public char execute(char[] letters, char target) {
int start = 0;
int end = letters.length - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (target < letters[mid]) {
end = mid - 1;
} else {
// If mid is the last element, it's possible for
// start to point to an index out of bound. In which
// case we wrap to index 0 for the answer.
start = mid + 1;
}
}
// If the target is greater than the last element
// start will be 1 more than the size of the arr
// to answer with the first element of the array.y
// So we use modulo to wrap back to index 0
// to answer with the first element of the array.
return letters[start % letters.length];
}
}