Smallest alphabet greater than a given character | C ++ 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 ; Take the first element as l and the rightmost element as r ; if this while condition does not satisfy simply return the first element . ; Return the smallest element ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; char 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 ; int ans = -1 ; while ( l <= r ) { int mid = ( l + r ) / 2 ; if ( alphabets [ mid ] > K ) { r = mid - 1 ; ans = mid ; } else l = mid + 1 ; } return alphabets [ ans ] ; } int main ( ) { vector < char > letters { ' A ' , ' K ' , ' S ' } ; char K = ' L ' ; char result = nextGreatestAlphabet ( letters , K ) ; cout << result << endl ; return 0 ; }