Skip to content

Commit a7c100c

Browse files
committed
Time: 48 ms (0%), Space: 18.1 MB (0%) - LeetHub
1 parent bd69bb2 commit a7c100c

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# time complexity: O(n*n!)
2+
# space complexity: O(n)
3+
class Solution:
4+
def lexGreaterPermutation(self, s: str, target: str) -> str:
5+
n = len(s)
6+
sCount = [0] * 26
7+
for c in s:
8+
sCount[ord(c) - ord('a')] += 1
9+
10+
result = None
11+
def backtrack(i: int, prefix: str, count: list, greater: bool):
12+
nonlocal result
13+
if result is not None and prefix >= result:
14+
return
15+
if i == n:
16+
if prefix > target:
17+
if result is None or prefix < result:
18+
result = prefix
19+
return
20+
for c in range(26):
21+
if count[c] == 0:
22+
continue
23+
currC = chr(c + ord('a'))
24+
if not greater and currC < target[i]:
25+
continue
26+
if not greater and currC == target[i]:
27+
count[c] -= 1
28+
backtrack(i + 1, prefix + currC, count, False)
29+
count[c] += 1
30+
elif greater or currC > target[i]:
31+
count[c] -= 1
32+
backtrack(i + 1, prefix + currC, count, True)
33+
count[c] += 1
34+
35+
backtrack(0, "", sCount, False)
36+
37+
if result:
38+
return result
39+
40+
return ""
41+
42+
43+
s = "abc"
44+
target = "bba"
45+
print(Solution().lexGreaterPermutation(s, target))
46+
s = "leet"
47+
target = "code"
48+
print(Solution().lexGreaterPermutation(s, target))
49+
s = "baba"
50+
target = "bbaa"
51+
print(Solution().lexGreaterPermutation(s, target))

0 commit comments

Comments
 (0)