Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit dd78621

Browse files
committed
O(n) time and O(1) space using linear search
1 parent 9c1520f commit dd78621

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'''
2+
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.
3+
4+
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.
5+
6+
7+
8+
Example 1:
9+
10+
Input: letters = ["c","f","j"], target = "a"
11+
Output: "c"
12+
Explanation: The smallest character that is lexicographically greater than 'a' in letters is 'c'.
13+
Example 2:
14+
15+
Input: letters = ["c","f","j"], target = "c"
16+
Output: "f"
17+
Explanation: The smallest character that is lexicographically greater than 'c' in letters is 'f'.
18+
Example 3:
19+
20+
Input: letters = ["x","x","y","y"], target = "z"
21+
Output: "x"
22+
Explanation: There are no characters in letters that is lexicographically greater than 'z' so we return letters[0].
23+
24+
25+
Constraints:
26+
27+
2 <= letters.length <= 104
28+
letters[i] is a lowercase English letter.
29+
letters is sorted in non-decreasing order.
30+
letters contains at least two different characters.
31+
target is a lowercase English letter.
32+
'''
33+
class Solution:
34+
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
35+
result,diff = letters[0],sys.maxsize
36+
for letter in letters:
37+
cur_diff = ord(letter) - ord(target)
38+
if cur_diff > 0 and cur_diff < diff:
39+
diff = cur_diff
40+
result = letter
41+
return result

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /