🔗 🔴 3518. Smallest Palindromic Rearrangement II

Problem Statement

題目簡述

給定一個回文字串 ss 與一個整數 kk,請回傳 ss 的所有互不相同的回文排列中,字典序第 kk 小(11-indexed)的字串。若不同的回文排列總數少於 kk,則回傳空字串 ""。

不同的重排方式若產生相同的回文字串,只計算一次。

Constraints

約束條件

  • 1≤∣s∣≤1041 \le |s| \le 10^4
  • ss 僅包含小寫英文字母
  • 保證 ss 本身是回文字串
  • 1≤k≤1061 \le k \le 10^6

思路:試填法 + 組合數學

因為輸入 ss 本身是回文字串,前半段 s[:n // 2] 的字元計數與正中間字元 mid = s[n // 2](若 nn 為奇數)都已固定,且前半段唯一決定後半段。因此問題等價於:求前半段(長度 m=⌊n/2⌋m = \lfloor n / 2 \rfloor)所有不重複排列中字典序第 kk 小的字串。

求字典序第 kk 小的排列,標準做法是從左到右逐位 試填法():

  • 先計算當前所有剩餘字元能組成的不重複排列總數;若總數小於 kk,直接回傳空字串 ""。
  • 接著對第 ii 位由 'a' 到 'z' 依序嘗試剩餘次數大於 00 的字元 cc,計算「第 ii 位固定填 cc 後,剩餘 m−i−1m - i - 1 個位置的排列總數 pp」:
    • 若 k≤pk \le p:第 kk 小的排列必然以 cc 作為第 ii 位,確定填入 cc 後進入下一位。
    • 若 k>pk > p:所有以 cc 開頭的排列都在目標之前,將 kk 減去 pp,復原 cc 的計數並嘗試下一個更大的字元。

剩餘長度為 m′m'、各字母出現次數分別為 a1,a2,…,ata_1, a_2, \dots, a_t(∑aj=m′\sum a_j = m')時,不重複的 多重集排列(Multiset Permutation) 總數為:

perm⁡=m′!a1! a2!⋯at!\operatorname{perm} = \frac{m'!}{a_1! \, a_2! \cdots a_t!}

接下來的關鍵在於如何高效計算 perm⁡\operatorname{perm}。

方法一:預處理階乘 + 增量更新(BigInt)

預先計算 0!0! 到 5000!5000!,並算出初始排列總數 perm⁡\operatorname{perm}。由於 mm 最大可達 50005000,若每次試填都從頭計算 perm⁡\operatorname{perm},大量的 大整數(BigInt) 乘除法會導致逾時。

注意到每次嘗試填入或退回單一字元 cc 時,只有總數 mm 與計數 cnt[c]\textit{cnt}[c] 各增減 11,其餘字母的階乘都不變,因此可直接對 perm⁡\operatorname{perm} 做增量更新,無需再乘除大數階乘:

  • 放入 cc(δ=−1\delta = -1):perm⁡′=perm⁡×cnt[c]/m\operatorname{perm}' = \operatorname{perm} \times \textit{cnt}[c] / m,再令 m←m−1m \leftarrow m - 1、cnt[c]←cnt[c]−1\textit{cnt}[c] \leftarrow \textit{cnt}[c] - 1;
  • 退回 cc(δ=+1\delta = +1):先令 m←m+1m \leftarrow m + 1、cnt[c]←cnt[c]+1\textit{cnt}[c] \leftarrow \textit{cnt}[c] + 1,再計算 perm⁡′=perm⁡×m/cnt[c]\operatorname{perm}' = \operatorname{perm} \times m / \textit{cnt}[c]。
常見陷阱

增量更新時必須先乘後除,否則會因分子分母已約分而無法整除,破壞精確值。

複雜度分析

  • 設 m=⌊n/2⌋m = \lfloor n / 2 \rfloor,∣Σ∣=26|\Sigma| = 26。
  • 時間複雜度:預處理階乘需計算至 m!m!,試填階段共執行至多 O(m⋅∣Σ∣)\mathcal{O}(m \cdot |\Sigma|) 次增量更新;每次僅對 perm⁡\operatorname{perm} 乘除一個不超過 mm 的小整數,但由於 perm⁡\operatorname{perm} 本身可達 O(mlog⁡m)\mathcal{O}(m \log m) 位元,整體常數仍高於方法二。
  • 空間複雜度:預處理階乘表包含 O(m)\mathcal{O}(m) 個大整數(總位元數為 O(m2log⁡m)\mathcal{O}(m^2 \log m))。

方法二:組合數連乘 + 超過 kk 截斷

關鍵觀察

題目保證 k≤106k \le 10^6,而試填時我們只關心 pp 是否達到 kk,不需要知道超過 kk 的精確值。只要計算過程中乘積一旦 ≥k\ge k,就可以直接截斷並回傳 kk,徹底避開大整數與溢位問題。

將多重集排列數改寫為逐字母選位置的 組合數(Binomial Coefficient) 連乘:

perm⁡=(n′c1)(n′−c1c2)⋯(ctct)\operatorname{perm} = \binom{n'}{c_1} \binom{n' - c_1}{c_2} \cdots \binom{c_t}{c_t}

計算單一組合數 (n′c)\binom{n'}{c} 時,利用對稱性令 r=min⁡(c,n′−c)r = \min(c, n' - c),改寫為:

(n′r)=n′1×n′−12×⋯×n′−r+1r\binom{n'}{r} = \frac{n'}{1} \times \frac{n' - 1}{2} \times \cdots \times \frac{n' - r + 1}{r}

依序從 i=1i = 1 到 rr 執行 res = res * (n' + 1 - i) // i:每一步的前綴乘積都恰好是整數 (n′i)\binom{n'}{i}(連續 ii 個整數中必有 ii 的倍數),因此無需浮點數也不會失真;一旦 res >= k 便立即回傳 k。

複雜度分析

  • 設 m=⌊n/2⌋m = \lfloor n / 2 \rfloor,∣Σ∣=26|\Sigma| = 26。
  • 時間複雜度:O(m⋅∣Σ∣⋅(∣Σ∣+log⁡k))\mathcal{O}(m \cdot |\Sigma| \cdot (|\Sigma| + \log k))。對每個 1≤r≤n′/21 \le r \le n' / 2 均有 (n′r)≥(2rr)≥2r\binom{n'}{r} \ge \binom{2r}{r} \ge 2^r,內層迴圈總步數至多 ⌈log⁡2k⌉\lceil \log_2 k \rceil 次即會觸發截斷,因此單次呼叫 perm 僅需 O(∣Σ∣+log⁡k)\mathcal{O}(|\Sigma| + \log k);共 mm 個位置、每位至多試填 ∣Σ∣|\Sigma| 次。
  • 空間複雜度:O(n+∣Σ∣)\mathcal{O}(n + |\Sigma|),用於儲存字元計數表與結果字串(不計輸出為 O(∣Σ∣)\mathcal{O}(|\Sigma|))。

Code

方法一:預處理階乘 + 增量更新(BigInt)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
initialized = False
MAX_N = (int(1e4) + 5) // 2
fact = [1] * MAX_N


# 直接用 BigInt 計算效率很低,但還是勉強能通過
def init():
global initialized
for i in range(2, MAX_N):
fact[i] = fact[i - 1] * i
initialized = True


class Solution:
def smallestPalindrome(self, s: str, k: int) -> str:
if not initialized:
init()

n = len(s)
# 因為題目確保給定的 s 也是回文,所以只需要統計前半段的字元數量即可
cnt = Counter(s[: n // 2])
mid = s[n // 2] if n & 1 else ""

m = n // 2

perm = fact[m]
for val in cnt.values():
perm //= fact[val]

if perm < k:
return ""

def update(ch: str, delta: int):
nonlocal perm, m
# 直接依 m 與 cnt[ch] 變化增量更新,先乘後除保證整除
if delta == 1:
m += 1
cnt[ch] += 1
perm = perm * m // cnt[ch]
else:
perm = perm * cnt[ch] // m
m -= 1
cnt[ch] -= 1

ans = []
for _ in range(m):
for ch in ascii_lowercase:
if cnt[ch] == 0:
continue
update(ch, -1)
if k <= perm:
ans.append(ch)
break
k -= perm
update(ch, 1)

ans = "".join(ans)
return ans + mid + ans[::-1]

方法二:組合數連乘 + 超過 kk 截斷

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution:
def smallestPalindrome(self, s: str, k: int) -> str:
n = len(s)
# 因為題目確保給定的 s 也是回文,所以只需要統計前半段的字元數量即可
cnt = Counter(s[: n // 2])
mid = s[n // 2] if n & 1 else ""

m = n // 2

def perm(n: int) -> int:
# C(n, c1) * C(n - c1, c2) * ... * C(n - c1 - c2 - ... - c(n-1), cn)
res = 1
for c in cnt.values():
if c == 0:
continue
# 用避免溢出的方式逐步計算 C(n, c)
m = min(c, n - c) # C(n, m) = C(n, n - m)
for i in range(1, m + 1):
res = res * (n + 1 - i) // i
if res >= k: # 若 res >= k,則直接回傳 k,避免溢出
return k
n -= c
return res

if perm(m) < k:
return ""

ans = []
for i in range(m):
for ch in ascii_lowercase:
if cnt[ch] == 0:
continue
cnt[ch] -= 1
p = perm(m - i - 1)
if k <= p:
ans.append(ch)
break
k -= p
cnt[ch] += 1

ans = "".join(ans)
return ans + mid + ans[::-1]

寫在最後

Cover Image Credit

The cover image was created by @柊栞zhongkan. All rights belong to the original artist.

If you are the copyright holder and believe this usage is inappropriate, please contact me by email or leave a comment. I will remove the image promptly.