- Related Questions & Answers
- 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
- JavaScript - Find the smallest n digit number or greater
- Python Indices of numbers greater than K
- Program to find size of smallest sublist whose sum at least target in Python
- Find Strings greater than a particular length in MongoDB?
- Python - Number of values greater than K in 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 - Get the Index of first element greater than K
- Program to find number not greater than n where all digits are non-decreasing in python
- Find the Next perfect square greater than a given number in C++
- Program to find kth smallest n length lexicographically smallest string in python
- Find a string such that every character is lexicographically greater than its immediate next character in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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"))

["c", "f", "j"], "a"

c

Advertisements