Nearest smaller character to a character K from a Sorted Array Last Updated : 28 Sep, 2021 Comments Improve Suggest changes Like Article Like Report Given a sorted array of characters arr[] and a character K, the task is to find the character with nearest smaller ASCII value than K from the given array. Print -1 if no character is found to be having smaller ASCII value than K.Examples: Input: arr[] = {'e', 'g', 't', 'y'}, K = 'u' Output: t Explanation: The character with nearest smaller ASCII value as of 'u' is 't'.Input: arr[] = {'e', 'g', 't', 'y'}, K = 'a' Output: -1 Explanation: No character exists with ASCII value smaller than that of 'a'. Naive Approach: The simplest approach to solve the problem is to iterate over the array and find the character having smaller ASCII value than that of K and the difference between their ASCII values is minimum. Time Complexity: O(N) Auxiliary Space: O(1) Efficient Approach: The idea is to use Binary Search to find out the floor element (largest character just smaller than key). Follow the steps below to solve the problem: Perform binary search on the array.Check if the current middle element(mid) is equal to the character K or not.If so, then set start to mid - 1, because we need to find just smaller element.If the arr[mid] is smaller than K, then store it in some variable say ch. Set start to mid + 1 to search for a smaller character nearer to K.Otherwise, set end to mid-1.Keep repeating the above steps. Finally, print the character obtained after completing the search. If no character is obtained, print -1. Below is the implementation of the above approach: C++ // C++ Program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to return the // nearest smaller character char bs(char ar[], int n, int ele) { int start = 0; int end = n - 1; // Stores the nearest smaller // character char ch = '@'; // Iterate till starts cross end while (start <= end) { // Find the mid element int mid = start + (end - start) / 2; // Check if K is found if (ar[mid] == ele) end = mid - 1; // Check if current character // is less than K else if (ar[mid] < ele) { ch = ar[mid]; // Increment the start start = mid + 1; } // Otherwise else // Increment end end = mid - 1; } // Return the character return ch; } // Driver Code int main() { char ar[] = { 'e', 'g', 't', 'y' }; int n = sizeof(ar) / sizeof(ar[0]); char K = 'u'; char ch = bs(ar, n, K); if (ch == '@') cout << "-1"; else cout << ch; return 0; } Java // Java program to implement // the above approach import java.util.*; class GFG{ // Function to return the // nearest smaller character static char bs(char ar[], int n, int ele) { int start = 0; int end = n - 1; // Stores the nearest smaller // character char ch = '@'; // Iterate till starts cross end while (start <= end) { // Find the mid element int mid = start + (end - start) / 2; // Check if K is found if (ar[mid] == ele) end = mid - 1; // Check if current character // is less than K else if (ar[mid] < ele) { ch = ar[mid]; // Increment the start start = mid + 1; } // Otherwise else // Increment end end = mid - 1; } // Return the character return ch; } // Driver Code public static void main(String[] args) { char ar[] = { 'e', 'g', 't', 'y' }; int n = ar.length; char K = 'u'; char ch = bs(ar, n, K); if (ch == '@') System.out.print("-1"); else System.out.print(ch); } } // This code is contributed by 29AjayKumar Python3 # Python3 program to implement # the above approach # Function to return the # nearest smaller character def bs(a, n, ele): start = 0 end = n - 1 # Stores the nearest smaller # character ch = '@' # Iterate till starts cross end while (start <= end): # Find the mid element mid = start + (end - start) // 2; # Check if K is found if(ar[mid] == ele): end = mid - 1 # Check if current character # is less than K elif(ar[mid] < ele): ch = ar[mid] # Increment the start start = mid + 1; # Otherwise else: # Increment end end = mid - 1; # Return the character return ch # Driver code if __name__=='__main__': ar = [ 'e', 'g', 't', 'y' ] n = len(ar) K = 'u'; ch = bs(ar, n, K); if (ch == '@'): print('-1') else: print(ch) # This code is contributed by rutvik_56 C# // C# program to implement // the above approach using System; class GFG{ // Function to return the // nearest smaller character static char bs(char []ar, int n, int ele) { int start = 0; int end = n - 1; // Stores the nearest smaller // character char ch = '@'; // Iterate till starts cross end while (start <= end) { // Find the mid element int mid = start + (end - start) / 2; // Check if K is found if (ar[mid] == ele) end = mid - 1; // Check if current character // is less than K else if (ar[mid] < ele) { ch = ar[mid]; // Increment the start start = mid + 1; } // Otherwise else // Increment end end = mid - 1; } // Return the character return ch; } // Driver Code public static void Main(String[] args) { char []ar = { 'e', 'g', 't', 'y' }; int n = ar.Length; char K = 'u'; char ch = bs(ar, n, K); if (ch == '@') Console.Write("-1"); else Console.Write(ch); } } // This code is contributed by 29AjayKumar JavaScript <script> // Javascript program for the above approach // Function to return the // nearest smaller letacter function bs(ar, n, ele) { let start = 0; let end = n - 1; // Stores the nearest smaller // letacter let ch = '@'; // Iterate till starts cross end while (start <= end) { // Find the mid element let mid = start + Math.floor((end - start) / 2); // Check if K is found if (ar[mid] == ele) end = mid - 1; // Check if current letacter // is less than K else if (ar[mid] < ele) { ch = ar[mid]; // Increment the start start = mid + 1; } // Otherwise else // Increment end end = mid - 1; } // Return the letacter return ch; } // Driver Code let ar = [ 'e', 'g', 't', 'y' ]; let n = ar.length; let K = 'u'; let ch = bs(ar, n, K); if (ch == '@') document.write("-1"); else document.write(ch); // This code is contributed by sanjoy_62. </script> Output: t Time Complexity: O(logN) Auxiliary Space: O(1) Comment More infoAdvertise with us Next Article Nearest smaller character to a character K from a Sorted Array S shauryarehangfg Follow Improve Article Tags : Strings Searching Competitive Programming C++ Programs DSA Arrays Binary Search ASCII +4 More Practice Tags : ArraysBinary SearchSearchingStrings Similar Reads Minimum operations required to convert all characters of a String to a given Character Given string str, a character ch, and an integer K, the task is to find the minimum number of operations required to convert all the characters of string str to ch. Each operation involves converting K closest characters from each side of the index i, i.e., characters in the indices [i - K, i + K] c 9 min read Kth most frequent Character in a given String Given a string str and an integer K, the task is to find the K-th most frequent character in the string. If there are multiple characters that can account as K-th most frequent character then, print any one of them.Examples: Input: str = "GeeksforGeeks", K = 3 Output: f Explanation: K = 3, here 'e' 6 min read Minimum length of Run Length Encoding possible by removing at most K characters from a given string Given a string S of length N, consisting of lowercase English alphabets only, the task is to find the minimum possible length of run-length-encoding that can be generated by removing at most K characters from the string S. Examples: Input: S = "abbbcdcdd", N = 9, K = 2 Output: 5 Explanation: One pos 10 min read C++ Program to Find closest number in array Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers. Examples: Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9} Target number = 11 Output : 9 9 is closest to 11 in given array Input :arr[] = {2, 5, 6, 7, 8, 8, 9}; 4 min read Sort the array of strings according to alphabetical order defined by another string Given a string str and an array of strings strArr[], the task is to sort the array according to the alphabetical order defined by str. Note: str and every string in strArr[] consists of only lower case alphabets. Examples: Input: str = "fguecbdavwyxzhijklmnopqrst", strArr[] = {"geeksforgeeks", "is", 5 min read Longest equal substring with cost less than K Given two strings X and Y of the same length, which consist of lowercase letters and also an integer K. The task is to find the maximum length up to which X can be changed to Y within the given cost K. The cost of changing a character is given by the absolute difference between the ASCII value of th 11 min read Longest substring with atmost K characters from the given set of characters Given a string S, an integer K and set of characters Q[], the task is to find the longest substring in string S which contains atmost K characters from the given character set Q[].Examples: Input: S = "normal", Q = {"a", "o", "n", "m", "r", "l"}, K = 1 Output: 1Explanation: All the characters in the 9 min read Shortest distance to every other character from given character Given a string S and a character X where X\varepsilon S[i] , for some 0\leq i \leq S.length()-1 . The task is to return an array of distances representing the shortest distance from the character X to every other character in the string. Examples: Input: S = "geeksforgeeks", X = 'e' Output: [1, 0, 0 15 min read Remove characters from a String that appears exactly K times Given a string of lowercase letters str of length N, the task is to reduce it by removing the characters which appear exactly K times in the string. Examples: Input: str = "geeksforgeeks", K = 2 Output: eeforee Input: str = "geeksforgeeks", K = 4 Output: gksforgks Approach: Create a hash table of si 5 min read Check whether a given array is a k sorted array or not Given an array of n distinct elements. Check whether the given array is a k sorted array or not. A k sorted array is an array where each element is at most k distances away from its target position in the sorted array. For example, let us consider k is 2, an element at index 7 in the sorted array, c 12 min read Like