- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Smallest Letter Greater Than Target in Python
Suppose we have a list of sorted characters’ letters. This is containing only lowercase letters, now we have a target letter t, we have to find the smallest element in the list that is larger than the given target.
And letters also wrap around. So, if the target is t = 'z' and letters = ['a', 'b'], the answer is 'a'.
So, if the input is like ["c", "f", "j"], t = 'a', then the output will be 'c'.
To solve this, we will follow these steps −
- l := 0
- r := size of letters - 1
- while l <= r, do
- mid :=(l + r) / 2 as integer
- if letters[mid] > target, then
- r := mid -1
- otherwise,
- l := mid + 1
- return letters[l mod size of letters]
Let us see the following implementation to get better understanding −
Example
class Solution: def nextGreatestLetter(self, letters, target): l = 0 r = len(letters) - 1 while l <= r: mid = (l + r)//2 if letters[mid] > target: r = mid -1 else: l = mid + 1 return letters[l % len(letters)] ob = Solution() print(ob.nextGreatestLetter(["c", "f", "j"], "a"))
Input
["c", "f", "j"], "a"
Output
c
- Related Articles
- Find Smallest Letter Greater Than Target in JavaScript
- Find smallest element greater than K in Python
- How to find the smallest number greater than x in Python?
- Program to find lowest sum of pairs greater than given target in Python
- Python - Find words greater than given length
- Smallest prime number just greater than the specified number in JavaScript
- Program to find size of smallest sublist whose sum at least target in Python
- Python – Remove characters greater than K
- Program to find sum of two numbers which are less than the target in Python
- JavaScript - Find the smallest n digit number or greater
- Python – Find the frequency of numbers greater than each element in a list
- How to get the smallest integer greater than or equal to a number in JavaScript?
- Program to find number of K-Length sublists whose average is greater or same as target in python
- Python Indices of numbers greater than K
- Python – Average of digit greater than K

Advertisements