744. Find Smallest Letter Greater Than Target
#binary-search
Problem
Intuition
Time Complexity
Space Complexity
Solution
class Solution {
public char nextGreatestLetter(char[] letters, char target) {
// n -> number of elements in nums
// Time Complexity: O(log n);
// Space Complexity: O(1), auxillary space, no extra space is used
// Start and end positions
int low = -1, high = letters.length;
while(low + 1 < high) {
int mid = low + (high-low)/2;
// This is ceiling of the target
// So we try to look out for first position which is greater than target
if(letters[mid] > target) {
high = mid;
} else {
low = mid;
}
}
// If we end up at last index position, it is given that letters[0] needs
// to be returned
if(high == letters.length) {
return letters[0];
}
return letters[high];
}
}
Last updated
Was this helpful?