Open In App

Smallest alphabet greater than a given character

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++ Program to find the smallest character
from the given set of letter, which is greater
than the target element */
#include <bits/stdc++.h>
using namespace std;
 
/* Returns the smallest character from the given
set 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 uppercase
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;
 
    // 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 Code
int 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 character
from the given set of letter, which is greater
than 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 Code
letters = ['A', 'r', 'z']
K = 'z'
 
# Function call
result = nextGreatestAlphabet(letters, K)
print(result)
 
# This code is contributed by Smitha




/* C# Program to find the smallest character
from the given set of letter, which is greater
than 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 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 */
      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>

Output
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.

Approach#2: Using upper

This approach compares each letter in the input list to the given character, finds the smallest letter greater than the given character, and prints it.

Algorithm

1. Convert all letters to uppercase for case-insensitive comparison.
2. Initialize the smallest greater letter to None.
3. Iterate over all letters in the list.
4. If the current letter is greater than the given character k and smaller than the current smallest greater letter, then update the smallest greater letter to the current letter.
5. If no greater letter was found, print “No greater letter found”, else print the smallest greater letter.




#include <iostream>
#include <vector>
#include <algorithm>
 
int main() {
    std::vector<std::string> letters = {"D", "J", "K"};
    std::string k = "B";
 
    // Convert all letters to uppercase for case-insensitive comparison
    std::transform(letters.begin(), letters.end(), letters.begin(), [](std::string& letter) {
        std::transform(letter.begin(), letter.end(), letter.begin(), ::toupper);
        return letter;
    });
    std::transform(k.begin(), k.end(), k.begin(), ::toupper);
 
    // Initialize the smallest greater letter to an empty string
    std::string smallestGreaterLetter = "";
 
    // Iterate over all letters
    for (const auto& letter : letters) {
        // If the letter is greater than k and smaller
        // than the current smallest greater letter
        if (letter > k && (smallestGreaterLetter.empty() || letter < smallestGreaterLetter)) {
            smallestGreaterLetter = letter;
        }
    }
 
    // If no greater letter was found, print "No greater letter found"
    if (smallestGreaterLetter.empty()) {
        std::cout << "No greater letter found" << std::endl;
    } else {
        std::cout << smallestGreaterLetter << std::endl;
    }
 
    return 0;
}




import java.util.ArrayList;
 
public class SmallestGreaterLetter {
    public static void main(String[] args) {
        ArrayList<String> letters = new ArrayList<>();
        letters.add("D");
        letters.add("J");
        letters.add("K");
        String k = "B";
 
        // Convert all letters to uppercase for case-insensitive comparison
        ArrayList<String> uppercaseLetters = new ArrayList<>();
        for (String letter : letters) {
            uppercaseLetters.add(letter.toUpperCase());
        }
        k = k.toUpperCase();
 
        // Initialize the smallest greater letter to null
        String smallestGreaterLetter = null;
 
        // Iterate over all letters
        for (String letter : uppercaseLetters) {
            // If the letter is greater than k and smaller
            // than the current smallest greater letter
            if (letter.compareTo(k) > 0 && (smallestGreaterLetter == null ||
                letter.compareTo(smallestGreaterLetter) < 0)) {
                smallestGreaterLetter = letter;
            }
        }
 
        // If no greater letter was found, print "No greater letter found"
        if (smallestGreaterLetter == null) {
            System.out.println("No greater letter found");
        } else {
            System.out.println(smallestGreaterLetter);
        }
    }
}




letters = ["D", "J", "K"]
k = "B"
 
# Convert all letters to uppercase for case-insensitive comparison
letters = [letter.upper() for letter in letters]
k = k.upper()
 
# Initialize the smallest greater letter to None
smallest_greater_letter = None
 
# Iterate over all letters
for letter in letters:
    # If the letter is greater than k and smaller than the current smallest greater letter
    if letter > k and (smallest_greater_letter is None or letter < smallest_greater_letter):
        smallest_greater_letter = letter
 
# If no greater letter was found, print "No greater letter found"
if smallest_greater_letter is None:
    print("No greater letter found")
else:
    print(smallest_greater_letter)




using System;
using System.Collections.Generic;
 
class SmallestGreaterLetter
{
    public static void Main(string[] args)
    {
        List<string> letters = new List<string>
        {
            "D",
            "J",
            "K"
        };
 
        string k = "B";
 
        // Convert all letters to uppercase for case-insensitive comparison
        List<string> uppercaseLetters = new List<string>();
        foreach (string letter in letters)
        {
            uppercaseLetters.Add(letter.ToUpper());
        }
        k = k.ToUpper();
 
        // Initialize the smallest greater letter to null
        string smallestGreaterLetter = null;
 
        // Iterate over all letters
        foreach (string letter in uppercaseLetters)
        {
            // If the letter is greater than k and smaller
            // than the current smallest greater letter
            if (string.Compare(letter, k) > 0 &&
                (smallestGreaterLetter == null || string.Compare(letter, smallestGreaterLetter) < 0))
            {
                smallestGreaterLetter = letter;
            }
        }
 
        // If no greater letter was found, print "No greater letter found"
        if (smallestGreaterLetter == null)
        {
            Console.WriteLine("No greater letter found");
        }
        else
        {
            Console.WriteLine(smallestGreaterLetter);
        }
    }
}




let letters = ["D", "J", "K"];
let k = "B";
 
// Convert all letters to uppercase for case-insensitive comparison
letters = letters.map(letter => letter.toUpperCase());
k = k.toUpperCase();
 
// Initialize the smallest greater letter to null
let smallestGreaterLetter = null;
 
// Iterate over all letters
letters.forEach(letter => {
    // If the letter is greater than k and smaller
    // than the current smallest greater letter
    if (letter > k && (smallestGreaterLetter === null || letter < smallestGreaterLetter)) {
        smallestGreaterLetter = letter;
    }
});
 
// If no greater letter was found, print "No greater letter found"
if (smallestGreaterLetter === null) {
    console.log("No greater letter found");
} else {
    console.log(smallestGreaterLetter);
}

Output
D







Time complexity: O(n), where n is the number of letters in the input list. This is because we iterate over all the letters in the list once.

Space complexity: O(1), as we are using a constant amount of extra memory to store the variables used in the algorithm, regardless of the size of the input list.


Article Tags :