Practice › Binary Search
Next Greatest Letter
Easy · Binary Search · Asked at LinkedIn, Amazon, Microsoft
The letters are sorted in non-decreasing order. Print the smallest letter in the list that is strictly greater than target. If there is none, wrap around and print the first letter.
Input
First line: n. Second line: the n letters separated by spaces. Third line: target.
Output
The answer letter.
Constraints
- 2 ≤ n ≤ 10^4
- lowercase letters
- at least two different letters
Binary search for the first letter > target (upper bound). If it is past the end, the answer is letters[0].
Example 1
Input
3 c f j a
Output
c
Example 2
Input
3 c f j c
Output
f
Example 3
Input
4 x x y y z
Output
x
Hints
- You need the first letter strictly greater than the target — an upper bound.
- If every letter is ≤ target, wrap around to the first letter.
Approach
Binary search for the first index whose letter is > target. If that index equals n (no such letter), the answer is letters[0]; otherwise it is letters[index].
Complexity: O(log n) time · O(n) to read the input
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<char> a(n);
for (auto &c : a) cin >> c;
char t;
cin >> t;
auto it = upper_bound(a.begin(), a.end(), t);
cout << (it == a.end() ? a[0] : *it) << "\n";
return 0;
}Python solution
import sys
from bisect import bisect_right
data = sys.stdin.read().split()
n = int(data[0])
a = data[1 : 1 + n]
t = data[1 + n]
i = bisect_right(a, t)
print(a[0] if i == n else a[i])Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
String[] a = br.readLine().trim().split("\\s+");
char t = br.readLine().trim().charAt(0);
int lo = 0, hi = n;
while (lo < hi) {
int m = (lo + hi) / 2;
if (a[m].charAt(0) <= t) lo = m + 1;
else hi = m;
}
System.out.println(lo == n ? a[0] : a[lo]);
}
}