LeetCode #3720 — MEDIUM

Lexicographically Smallest Permutation Greater Than Target

Move from brute-force thinking to an efficient approach using hash map strategy.

Solve on LeetCode
The Problem

Problem Statement

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:

  • The permutations of s (in lexicographical order) are "abc", "acb", "bac", "bca", "cab", and "cba".
  • The lexicographically smallest permutation that is strictly greater than target is "bca".

Example 2:

Input: s = "leet", target = "code"

Output: "eelt"

Explanation:

  • The permutations of s (in lexicographical order) are "eelt", "eetl", "elet", "elte", "etel", "etle", "leet", "lete", "ltee", "teel", "tele", and "tlee".
  • The lexicographically smallest permutation that is strictly greater than target is "eelt".

Example 3:

Input: s = "baba", target = "bbaa"

Output: ""

Explanation:

  • The permutations of s (in lexicographical order) are "aabb", "abab", "abba", "baab", "baba", and "bbaa".
  • None of them is lexicographically strictly greater than target. Therefore, the answer is "".

Constraints:

  • 1 <= s.length == target.length <= 300
  • s and target consist of only lowercase English letters.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

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.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Hash Map · Greedy

Example 1

"abc"
"bba"

Example 2

"leet"
"code"

Example 3

"baba"
"bbaa"
Step 02

Core Insight

What unlocks the optimal approach

  • Maintain frequency counts of <code>s</code>.
  • Walk left-to-right; if equal to <code>target[i]</code> is possible, take it and continue.
  • If not, try the smallest letter strictly greater than <code>target[i]</code>.
  • If neither, backtrack left to the most recent index where you matched <code>target</code> and try to bump there.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

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 ""
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n log n)
Space
O(1)

Approach Breakdown

EXHAUSTIVE
O(2ⁿ) time
O(n) space

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
O(n log n) time
O(1) 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.

Shortcut: Sort + single pass → O(n log n). If no sort needed → O(n). The hard part is proving it works.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

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.

Using greedy without proof

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.