Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
You are given two strings s and target, both having length n, consisting of lowercase English letters.
Return the lexicographically smallest permutation of s that is strictly greater than target. If no permutation of s is lexicographically strictly greater than target, return an empty string.
A string a is lexicographically strictly greater than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b.
Example 1:
Input: s = "abc", target = "bba"
Output: "bca"
Explanation:
s (in lexicographical order) are "abc", "acb", "bac", "bca", "cab", and "cba".target is "bca".Example 2:
Input: s = "leet", target = "code"
Output: "eelt"
Explanation:
s (in lexicographical order) are "eelt", "eetl", "elet", "elte", "etel", "etle", "leet", "lete", "ltee", "teel", "tele", and "tlee".target is "eelt".Example 3:
Input: s = "baba", target = "bbaa"
Output: ""
Explanation:
s (in lexicographical order) are "aabb", "abab", "abba", "baab", "baba", and "bbaa".target. Therefore, the answer is "".Constraints:
1 <= s.length == target.length <= 300s and target consist of only lowercase English letters.Problem summary: You are given two strings s and target, both having length n, consisting of lowercase English letters. Return the lexicographically smallest permutation of s that is strictly greater than target. If no permutation of s is lexicographically strictly greater than target, return an empty string. A string a is lexicographically strictly greater than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Greedy
"abc" "bba"
"leet" "code"
"baba" "bbaa"
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3720: Lexicographically Smallest Permutation Greater Than Target
// Auto-generated Java example from go.
class Solution {
public void exampleSolution() {
}
}
// Reference (go):
// // Accepted solution for LeetCode #3720: Lexicographically Smallest Permutation Greater Than Target
// package main
//
// import "strings"
//
// // https://space.bilibili.com/206214
// func lexGreaterPermutation1(s, target string) string {
// left := make([]int, 26)
// for i, b := range s {
// left[b-'a']++
// left[target[i]-'a']-- // 消耗 s 中的一个字母 target[i]
// }
//
// next:
// for i := len(s) - 1; i >= 0; i-- {
// b := target[i] - 'a'
// left[b]++ // 撤销消耗
// for _, c := range left {
// if c < 0 { // [0,i-1] 无法做到全部一样
// continue next
// }
// }
//
// // 把 target[i] 增大到 j
// for j := b + 1; j < 26; j++ {
// if left[j] == 0 {
// continue
// }
//
// left[j]--
// ans := []byte(target[:i+1])
// ans[i] = 'a' + j
//
// for k, c := range left {
// ch := string('a' + byte(k))
// ans = append(ans, strings.Repeat(ch, c)...)
// }
// return string(ans)
// }
// // 增大失败,继续枚举
// }
// return ""
// }
//
// func lexGreaterPermutation(s, target string) string {
// left := make([]int, 26)
// for i, b := range s {
// left[b-'a']++
// left[target[i]-'a']--
// }
//
// neg, mx := 0, byte(0)
// for i, cnt := range left {
// if cnt < 0 {
// neg++ // 统计 left 中的负数个数
// } else if cnt > 0 {
// mx = max(mx, byte(i))
// }
// }
//
// for i := len(s) - 1; i >= 0; i-- {
// b := target[i] - 'a'
// left[b]++ // 撤销消耗
//
// if left[b] == 0 {
// neg--
// } else if left[b] == 1 {
// mx = max(mx, b)
// }
//
// // left 有负数 or 没有大于 target[i] 的字母
// if neg > 0 || b >= mx {
// continue
// }
//
// j := b + 1
// for left[j] == 0 {
// j++
// }
//
// // 把 target[i] 增大到 j
// left[j]--
// ans := []byte(target[:i+1])
// ans[i] = 'a' + byte(j)
//
// for k, c := range left {
// ch := string('a' + byte(k))
// ans = append(ans, strings.Repeat(ch, c)...)
// }
// return string(ans)
// }
// return ""
// }
// Accepted solution for LeetCode #3720: Lexicographically Smallest Permutation Greater Than Target
package main
import "strings"
// https://space.bilibili.com/206214
func lexGreaterPermutation1(s, target string) string {
left := make([]int, 26)
for i, b := range s {
left[b-'a']++
left[target[i]-'a']-- // 消耗 s 中的一个字母 target[i]
}
next:
for i := len(s) - 1; i >= 0; i-- {
b := target[i] - 'a'
left[b]++ // 撤销消耗
for _, c := range left {
if c < 0 { // [0,i-1] 无法做到全部一样
continue next
}
}
// 把 target[i] 增大到 j
for j := b + 1; j < 26; j++ {
if left[j] == 0 {
continue
}
left[j]--
ans := []byte(target[:i+1])
ans[i] = 'a' + j
for k, c := range left {
ch := string('a' + byte(k))
ans = append(ans, strings.Repeat(ch, c)...)
}
return string(ans)
}
// 增大失败,继续枚举
}
return ""
}
func lexGreaterPermutation(s, target string) string {
left := make([]int, 26)
for i, b := range s {
left[b-'a']++
left[target[i]-'a']--
}
neg, mx := 0, byte(0)
for i, cnt := range left {
if cnt < 0 {
neg++ // 统计 left 中的负数个数
} else if cnt > 0 {
mx = max(mx, byte(i))
}
}
for i := len(s) - 1; i >= 0; i-- {
b := target[i] - 'a'
left[b]++ // 撤销消耗
if left[b] == 0 {
neg--
} else if left[b] == 1 {
mx = max(mx, b)
}
// left 有负数 or 没有大于 target[i] 的字母
if neg > 0 || b >= mx {
continue
}
j := b + 1
for left[j] == 0 {
j++
}
// 把 target[i] 增大到 j
left[j]--
ans := []byte(target[:i+1])
ans[i] = 'a' + byte(j)
for k, c := range left {
ch := string('a' + byte(k))
ans = append(ans, strings.Repeat(ch, c)...)
}
return string(ans)
}
return ""
}
# Accepted solution for LeetCode #3720: Lexicographically Smallest Permutation Greater Than Target
# Time: O(26 * n)
# Space: O(26)
# freq table, greedy
class Solution(object):
def lexGreaterPermutation(self, s, target):
"""
:type s: str
:type target: str
:rtype: str
"""
def nxt(cnt, x):
for i in xrange(ord(x)-ord('a')+1, len(cnt)):
if not cnt[i]:
continue
return chr(ord('a')+i)
return ' '
cnt = [0]*26
for x in s:
cnt[ord(x)-ord('a')] += 1
tmp = cnt[:]
j = -1
for i, x in enumerate(target):
y = nxt(tmp, x)
if y != ' ':
j = i
if not tmp[ord(x)-ord('a')]:
break
tmp[ord(x)-ord('a')] -= 1
if j == -1:
return ""
result = []
for i in xrange(j):
result.append(target[i])
cnt[ord(target[i])-ord('a')] -= 1
y = nxt(cnt, target[j])
result.append(y)
cnt[ord(y)-ord('a')] -= 1
for i in xrange(len(cnt)):
for _ in xrange(cnt[i]):
result.append(chr(ord('a')+i))
cnt[i] -= 1
return "".join(result)
// Accepted solution for LeetCode #3720: Lexicographically Smallest Permutation Greater Than Target
// Rust example auto-generated from go reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (go):
// // Accepted solution for LeetCode #3720: Lexicographically Smallest Permutation Greater Than Target
// package main
//
// import "strings"
//
// // https://space.bilibili.com/206214
// func lexGreaterPermutation1(s, target string) string {
// left := make([]int, 26)
// for i, b := range s {
// left[b-'a']++
// left[target[i]-'a']-- // 消耗 s 中的一个字母 target[i]
// }
//
// next:
// for i := len(s) - 1; i >= 0; i-- {
// b := target[i] - 'a'
// left[b]++ // 撤销消耗
// for _, c := range left {
// if c < 0 { // [0,i-1] 无法做到全部一样
// continue next
// }
// }
//
// // 把 target[i] 增大到 j
// for j := b + 1; j < 26; j++ {
// if left[j] == 0 {
// continue
// }
//
// left[j]--
// ans := []byte(target[:i+1])
// ans[i] = 'a' + j
//
// for k, c := range left {
// ch := string('a' + byte(k))
// ans = append(ans, strings.Repeat(ch, c)...)
// }
// return string(ans)
// }
// // 增大失败,继续枚举
// }
// return ""
// }
//
// func lexGreaterPermutation(s, target string) string {
// left := make([]int, 26)
// for i, b := range s {
// left[b-'a']++
// left[target[i]-'a']--
// }
//
// neg, mx := 0, byte(0)
// for i, cnt := range left {
// if cnt < 0 {
// neg++ // 统计 left 中的负数个数
// } else if cnt > 0 {
// mx = max(mx, byte(i))
// }
// }
//
// for i := len(s) - 1; i >= 0; i-- {
// b := target[i] - 'a'
// left[b]++ // 撤销消耗
//
// if left[b] == 0 {
// neg--
// } else if left[b] == 1 {
// mx = max(mx, b)
// }
//
// // left 有负数 or 没有大于 target[i] 的字母
// if neg > 0 || b >= mx {
// continue
// }
//
// j := b + 1
// for left[j] == 0 {
// j++
// }
//
// // 把 target[i] 增大到 j
// left[j]--
// ans := []byte(target[:i+1])
// ans[i] = 'a' + byte(j)
//
// for k, c := range left {
// ch := string('a' + byte(k))
// ans = append(ans, strings.Repeat(ch, c)...)
// }
// return string(ans)
// }
// return ""
// }
// Accepted solution for LeetCode #3720: Lexicographically Smallest Permutation Greater Than Target
// Auto-generated TypeScript example from go.
function exampleSolution(): void {
}
// Reference (go):
// // Accepted solution for LeetCode #3720: Lexicographically Smallest Permutation Greater Than Target
// package main
//
// import "strings"
//
// // https://space.bilibili.com/206214
// func lexGreaterPermutation1(s, target string) string {
// left := make([]int, 26)
// for i, b := range s {
// left[b-'a']++
// left[target[i]-'a']-- // 消耗 s 中的一个字母 target[i]
// }
//
// next:
// for i := len(s) - 1; i >= 0; i-- {
// b := target[i] - 'a'
// left[b]++ // 撤销消耗
// for _, c := range left {
// if c < 0 { // [0,i-1] 无法做到全部一样
// continue next
// }
// }
//
// // 把 target[i] 增大到 j
// for j := b + 1; j < 26; j++ {
// if left[j] == 0 {
// continue
// }
//
// left[j]--
// ans := []byte(target[:i+1])
// ans[i] = 'a' + j
//
// for k, c := range left {
// ch := string('a' + byte(k))
// ans = append(ans, strings.Repeat(ch, c)...)
// }
// return string(ans)
// }
// // 增大失败,继续枚举
// }
// return ""
// }
//
// func lexGreaterPermutation(s, target string) string {
// left := make([]int, 26)
// for i, b := range s {
// left[b-'a']++
// left[target[i]-'a']--
// }
//
// neg, mx := 0, byte(0)
// for i, cnt := range left {
// if cnt < 0 {
// neg++ // 统计 left 中的负数个数
// } else if cnt > 0 {
// mx = max(mx, byte(i))
// }
// }
//
// for i := len(s) - 1; i >= 0; i-- {
// b := target[i] - 'a'
// left[b]++ // 撤销消耗
//
// if left[b] == 0 {
// neg--
// } else if left[b] == 1 {
// mx = max(mx, b)
// }
//
// // left 有负数 or 没有大于 target[i] 的字母
// if neg > 0 || b >= mx {
// continue
// }
//
// j := b + 1
// for left[j] == 0 {
// j++
// }
//
// // 把 target[i] 增大到 j
// left[j]--
// ans := []byte(target[:i+1])
// ans[i] = 'a' + byte(j)
//
// for k, c := range left {
// ch := string('a' + byte(k))
// ans = append(ans, strings.Repeat(ch, c)...)
// }
// return string(ans)
// }
// return ""
// }
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.