Find Smallest Letter Greater Than Target

Given a list of sorted characters letters containing only lowercase letters, and given a target letter target, find the smallest element in the list that is larger than the given target.
Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'.

Example:

Input: letters={'c','f','j'}, target='a'
Output: c

Approach

Java


public class FindNextGreatestLetter {
    public static void main(String[] args) {
        char[] letters = { 'c''f''j' };
        char target = 'a';
        System.out.println(nextGreatestLetter(letters, target));
    }

    static char nextGreatestLetter(char[] letterschar t) {
        int low = 0, high = letters.length - 1;
        char ans = '#';
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (letters[mid] > t) {
                high = mid - 1;
                ans = letters[mid];
            } else
                low = mid + 1;
        }
        if (ans == '#')
            return letters[0];
        return ans;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

char nextGreatestLetter(vector<char>& letterschar t
{
     
        int low=0,high=letters.size()-1;
        char ans='#';
        while(low<=high)
        {
           int mid=low+(high-low)/2;
           if(letters[mid]>t)
           {
               high=mid-1;
               ans=letters[mid];
           }
          else
              low=mid+1;
        }
        if(ans=='#')
              return letters[0];
        return ans;
}

int main()
{
    vector<charletters={'c','f','j'};
    char target='a';
    cout<<nextGreatestLetter(letters,target);
    return 0;
}


No comments:

Post a Comment