Smallest alphabet greater than a given character - GeeksforGeeks

27 May, 2021
Given a list of sorted characters consisting of both Uppercase and Lowercase Alphabets and a particular target value, say K, the task is to find the smallest element in the list that is larger than K. Letters also wrap around. For example, if K = ‘z’ and letters = [‘A’, ‘r’, ‘z’], then the answer would be ‘A’.
Examples:  
Input : Letters = ["D", "J", "K"]
        K = "B"
Output: 'D'
Explanation:
The Next greater character of "B" is 'D'
since it is the smallest element from the 
set of given letters, greater than "B".

Input:  Letters = ["h", "n", "s"]
        K = "t"
Output: 'h'
Prerequisites: Binary Search
Approach: Binary Search can be applied to find the index of the smallest character in the given Set of Letters such that the character at that index is greater than K. If the element at the current mid is smaller than or equal to K, binary search is applied on the Right half, else it is applied on the left half. 
C++
Java
Python 3
C#
Javascript
/* C++ Program to find the smallest characterfrom the given set of letter, which is greaterthan the target element */#include <bits/stdc++.h>using namespace std; /* Returns the smallest character from the givenset of letters that is greater than K */ // In this code we consider only uppercase characters or only lowercase characters// Incase if we have mixed characters then we//convert all either into lowercase or uppercasechar nextGreatestAlphabet(vector<char>& alphabets, char K){    int n= alphabets.size();    if(K>=alphabets[n-1]) return alphabets[0];          int l = 0, r = alphabets.size() - 1;     // Take the first element as l and    // the rightmost element as r    int ans = -1;    while (l <= r) {         // if this while condition does not satisfy        // simply return the first element.        int mid = (l + r) / 2;        if (alphabets[mid] > K)        {            r = mid - 1;            ans = mid;        }        else            l = mid + 1;    }     // Return the smallest element    return alphabets[ans];} // Driver Codeint main(){    vector<char> letters{ 'A', 'K', 'S' };    char K = 'L';     // Function call    char result = nextGreatestAlphabet(letters, K);    cout << result << endl;    return 0;}
/* Java Program to find the smallest characterfrom the given set of letter, which is greaterthan the target element */ class GFG{     /* Returns the smallest character from the given    set of letters that is greater than K */    static char nextGreatestAlphabet(char alphabets[],                                     char K)    {      int n = alphabets.length;      if(K>=alphabets[n-1])        return alphabets[0];         int l = 0, r = alphabets.length - 1;              int ans = -1;        // Take the first element as l and        // the rightmost element as r        while (l <= r)        {            // if this while condition does not            // satisfy simply return the first            // element.            int mid = (l + r) / 2;            if (alphabets[mid] > K)            {                r = mid - 1;                ans = mid;            }            else                l = mid + 1;        }         // Return the smallest element        return alphabets[ans];    }     // Driver Code    public static void main(String[] args)    {        char letters[] = { 'A', 'r', 'z' };        char K = 'z';        char result = nextGreatestAlphabet(letters, K);         // Function call        System.out.println(result);    }} // This code is contributed by Smitha.
# Python 3 Program to find the smallest# character from the given set of letter,# which is greater than the target# element */ # Returns the smallest character from# the given set of letters that is# greater than K  def nextGreatestAlphabet(alphabets, K):     n = len(alphabets)    if(K >= alphabets[n-1]):       return alphabets[0]    l = 0    r = len(alphabets) - 1    ans = -1    # Take the first element as l and    # the rightmost element as r    while (l <= r):         # if this while condition does        # not satisfy simply return the        # first element.        mid = int((l + r) / 2)         if (alphabets[mid] > K):            r = mid - 1            ans = mid        else:            l = mid + 1     # Return the smallest element    if (alphabets[ans] < K):        return alphabets[0]    else:        return alphabets[ans]  # Driver Codeletters = ['A', 'r', 'z']K = 'z' # Function callresult = nextGreatestAlphabet(letters, K)print(result) # This code is contributed by Smitha
/* C# Program to find the smallest characterfrom the given set of letter, which is greaterthan the target element */using System; class GFG {     /* Returns the smallest character from the given    set of letters that is greater than K */    static char nextGreatestAlphabet(char[] alphabets,                                     char K)    {         int n= alphabets.Length;        if(K >= alphabets[n-1])          return alphabets[0];        int l = 0, r = alphabets.Length - 1;        int ans = -1;        // Take the first element as l and        // the rightmost element as r        while (l <= r)        {             // if this while condition does not            // satisfy simply return the first            // element.            int mid = (l + r) / 2;             if (alphabets[mid] > K)            {                ans = mid;                r = mid - 1;            }            else                l = mid + 1;        }         // Return the smallest element        return alphabets[ans];    }     // Driver Code    public static void Main()    {        char[] letters = { 'A', 'r', 'z' };        char K = 'z';               // Function call        char result = nextGreatestAlphabet(letters, K);         Console.Write(result);    }} // This code is contributed by Smitha
<script> /* JavaScript Program to find the smallest characterfrom the given set of letter, which is greaterthan the target element */       /* Returns the smallest character from the given    set of letters that is greater than K */      function nextGreatestAlphabet(alphabets, K)      {        var l = 0,          r = alphabets.length - 1;        var ans = -1;                 // Take the first element as l and        // the rightmost element as r        while (l <= r)        {          // if this while condition does not          // satisfy simply return the first          // element.          var mid = (l + r) / 2;           if (alphabets[mid] > K) {            ans = mid;            r = mid - 1;          } else l = mid + 1;        }         // Return the smallest element        return alphabets[ans];      }       // Driver Code      var letters = ["A", "K", "S"];      var K = "L";       // Function call      document.write(nextGreatestAlphabet(letters, K));       </script>
S
 The Time Complexity of the above approach is, O(log N) where N is the number of characters in the given set of Letters.
Smitha Dinesh Semwal
ankitaankit1311
adityamishra120799
ferryrules
rdtank
bss12
Binary Search
Strings
Strings
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 String Coding Problems for Interviews
Hill Cipher
Naive algorithm for Pattern Searching
Vigenère Cipher
How to Append a Character to a String in C
Convert character array to string in C++
Print all subsequences of a string
Converting Roman Numerals to Decimal lying between 1 to 3999
sprintf() in C
Find frequency of each word in a string in Python