The Fake Geek's blog: Next Character
* Return the smallest character that is strictly larger than the search character,
* If no such character exists, return the smallest character in the array
* @param sortedStr : sorted list of letters, sorted in ascending order.
* @param c : character for which we are searching.
* Given the following inputs we expect the corresponding output:
* ['c', 'f', 'j', 'p', 'v'], 'a' => 'c'
* ['c', 'f', 'j', 'p', 'v'], 'c' => 'f'
* ['c', 'f', 'j', 'p', 'v'], 'k' => 'p'
* ['c', 'f', 'j', 'p', 'v'], 'z' => 'c' // The wrap around case
* ['c', 'f', 'k'], 'f' => 'k'
* ['c', 'f', 'k'], 'c' => 'f'
* ['c', 'f', 'k'], 'd' => 'f'
The problem doesn't clarify if duplicates are allowed in the array. So I wrote two.
Duplicates are allowed (not much difference though...)
Read full article from The Fake Geek's blog: Next Character
* Return the smallest character that is strictly larger than the search character,
* If no such character exists, return the smallest character in the array
* @param sortedStr : sorted list of letters, sorted in ascending order.
* @param c : character for which we are searching.
* Given the following inputs we expect the corresponding output:
* ['c', 'f', 'j', 'p', 'v'], 'a' => 'c'
* ['c', 'f', 'j', 'p', 'v'], 'c' => 'f'
* ['c', 'f', 'j', 'p', 'v'], 'k' => 'p'
* ['c', 'f', 'j', 'p', 'v'], 'z' => 'c' // The wrap around case
* ['c', 'f', 'k'], 'f' => 'k'
* ['c', 'f', 'k'], 'c' => 'f'
* ['c', 'f', 'k'], 'd' => 'f'
The problem doesn't clarify if duplicates are allowed in the array. So I wrote two.
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
| public class SmallestCharacter { public char nextChar( char [] list, char c) { if (list == null || list.length == 0) throw new IllegalArgumentException( "Null or empty list!" ); int start = 0; int end = list.length - 1; if (c < list[0] || c >= list[list.length - 1]) return list[0]; while (start < end) { int mid = (start + end) / 2; if (c == list[mid]) { //System.out.println(mid + ": " + list[mid]); return list[mid + 1]; } else if (c < list[mid]) { //System.out.println("smaller: " + mid); end = mid - 1; } else { //System.out.println("greater: " + mid); start = mid + 1; } } if (list[start] == c) return list[start + 1]; return list[start]; } } |
Duplicates are allowed (not much difference though...)
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
| public char nextChar2( char [] list, char c) { if (list == null || list.length == 0) throw new IllegalArgumentException( "Null or empty list!" ); int start = 0; int end = list.length - 1; if (c < list[0] || c >= list[list.length - 1]) return list[0]; while (start < end) { int mid = (start + end) / 2; if (c == list[mid]) { if (list[mid + 1] > c) return list[mid + 1]; else start = mid + 1; } else if (c < list[mid]) { end = mid - 1; } else start = mid + 1; } if (list[start] == c) return list[start + 1]; return list[start]; } |