
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
Advertisements