Skip to content

Commit

Permalink
added new question (Find next greatest letter)to Binary search quest…
Browse files Browse the repository at this point in the history
…ions
  • Loading branch information
b-izad committed Jun 21, 2023
1 parent 45ca340 commit 75534e0
Showing 1 changed file with 39 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'''744. Find Smallest Letter Greater Than Target
You are given an array of characters letters that is sorted in non-decreasing order, and a character target. There are at least two different characters in letters.
Return the smallest character in letters that is lexicographically greater than target. If such a character does not exist, return the first character in letters.
Example 1:
Input: letters = ["c","f","j"], target = "a"
Output: "c"
Explanation: The smallest character that is lexicographically greater than 'a' in letters is 'c'.
Example 2:
Input: letters = ["c","f","j"], target = "c"
Output: "f"
Explanation: The smallest character that is lexicographically greater than 'c' in letters is 'f'.'''

class Solution:
def nextGreatestLetter(self, letters: List[str], target: str) -> str:

start = 0
end = len(letters) - 1

if target < letters[start] or target >= letters[end]:
return letters[start]

while start <= end:
middle = start + (end - start) // 2
candidate = letters[middle]

if target < candidate:
end = middle - 1

if target >= candidate:
start = middle + 1

return letters[start]

0 comments on commit 75534e0

Please sign in to comment.