Find Smallest Letter Greater Than Target (LeetCode)

  Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in the array that is larger than target.

Note that the letters wrap around.

  • For example, if target == 'z' and letters == ['a', 'b'], the answer is 'a'.

 

Example 1:

Input: letters = ["c","f","j"], target = "a"
Output: "c"
Input: letters = ["c","f","j"], target = "j"
Output: "c"
Solution(Java)
class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
        int start=0, end= letters.length-1;
        while(start<=end){
            int mid=start+(end-start)/2;
            if(letters[mid]>target)
            end=mid-1;
            else
            start=mid+1;         
        }
        return letters[start%letters.length];    
    }
}

Comments

Popular posts from this blog

Final Value of Variable After Performing Operations (LeetCode)

Java Output Formatting | Hackerrank

China will fight six wars in the next 50 years!