In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that 'a' is after 'z'). For example, replacing 'a' with the next letter results in 'b', and replacing 'a' with the previous letter results in 'z'. Similarly, replacing 'z' with the next letter results in 'a', and replacing 'z' with the previous letter results in 'y'.
Return the length of the longest palindromicsubsequence of s that can be obtained after performing at mostk operations.
Example 1:
Input:s = "abced", k = 2
Output:3
Explanation:
Replace s[1] with the next letter, and s becomes "acced".
Replace s[4] with the previous letter, and s becomes "accec".
The subsequence "ccc" forms a palindrome of length 3, which is the maximum.
Example 2:
Input:s = "aaazzz", k = 4
Output: 6
Explanation:
Replace s[0] with the previous letter, and s becomes "zaazzz".
Replace s[4] with the next letter, and s becomes "zaazaz".
Replace s[3] with the next letter, and s becomes "zaaaaz".
Problem summary: You are given a string s and an integer k. In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that 'a' is after 'z'). For example, replacing 'a' with the next letter results in 'b', and replacing 'a' with the previous letter results in 'z'. Similarly, replacing 'z' with the next letter results in 'a', and replacing 'z' with the previous letter results in 'y'. Return the length of the longest palindromic subsequence of s that can be obtained after performing at most k operations.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
"abced"
2
Example 2
"aaazzz"
4
Step 02
Core Insight
What unlocks the optimal approach
Use dynamic programming.
<code>dp[i][j][k]</code> is the length of the longest palindromic subsequence in substring <code>[i..j]</code> with cost at most <code>k</code>.
<code>dp[i][j][k] = max(dp[i + 1][j][k], dp[i][j - 1][k], dp[i + 1][j - 1][k - dist(s[i], s[j])] + 2)</code>, where <code>dist(x, y)</code> is the minimum cyclic distance between <code>x</code> and <code>y</code>.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
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 #3472: Longest Palindromic Subsequence After at Most K Operations
class Solution {
private char[] s;
private Integer[][][] f;
public int longestPalindromicSubsequence(String s, int k) {
this.s = s.toCharArray();
int n = s.length();
f = new Integer[n][n][k + 1];
return dfs(0, n - 1, k);
}
private int dfs(int i, int j, int k) {
if (i > j) {
return 0;
}
if (i == j) {
return 1;
}
if (f[i][j][k] != null) {
return f[i][j][k];
}
int res = Math.max(dfs(i + 1, j, k), dfs(i, j - 1, k));
int d = Math.abs(s[i] - s[j]);
int t = Math.min(d, 26 - d);
if (t <= k) {
res = Math.max(res, 2 + dfs(i + 1, j - 1, k - t));
}
f[i][j][k] = res;
return res;
}
}
// Accepted solution for LeetCode #3472: Longest Palindromic Subsequence After at Most K Operations
func longestPalindromicSubsequence(s string, k int) int {
n := len(s)
f := make([][][]int, n)
for i := range f {
f[i] = make([][]int, n)
for j := range f[i] {
f[i][j] = make([]int, k+1)
for l := range f[i][j] {
f[i][j][l] = -1
}
}
}
var dfs func(int, int, int) int
dfs = func(i, j, k int) int {
if i > j {
return 0
}
if i == j {
return 1
}
if f[i][j][k] != -1 {
return f[i][j][k]
}
res := max(dfs(i+1, j, k), dfs(i, j-1, k))
d := abs(int(s[i]) - int(s[j]))
t := min(d, 26-d)
if t <= k {
res = max(res, 2+dfs(i+1, j-1, k-t))
}
f[i][j][k] = res
return res
}
return dfs(0, n-1, k)
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #3472: Longest Palindromic Subsequence After at Most K Operations
class Solution:
def longestPalindromicSubsequence(self, s: str, k: int) -> int:
@cache
def dfs(i: int, j: int, k: int) -> int:
if i > j:
return 0
if i == j:
return 1
res = max(dfs(i + 1, j, k), dfs(i, j - 1, k))
d = abs(s[i] - s[j])
t = min(d, 26 - d)
if t <= k:
res = max(res, dfs(i + 1, j - 1, k - t) + 2)
return res
s = list(map(ord, s))
n = len(s)
ans = dfs(0, n - 1, k)
dfs.cache_clear()
return ans
// Accepted solution for LeetCode #3472: Longest Palindromic Subsequence After at Most K Operations
// Rust example auto-generated from java 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 (java):
// // Accepted solution for LeetCode #3472: Longest Palindromic Subsequence After at Most K Operations
// class Solution {
// private char[] s;
// private Integer[][][] f;
//
// public int longestPalindromicSubsequence(String s, int k) {
// this.s = s.toCharArray();
// int n = s.length();
// f = new Integer[n][n][k + 1];
// return dfs(0, n - 1, k);
// }
//
// private int dfs(int i, int j, int k) {
// if (i > j) {
// return 0;
// }
// if (i == j) {
// return 1;
// }
// if (f[i][j][k] != null) {
// return f[i][j][k];
// }
// int res = Math.max(dfs(i + 1, j, k), dfs(i, j - 1, k));
// int d = Math.abs(s[i] - s[j]);
// int t = Math.min(d, 26 - d);
// if (t <= k) {
// res = Math.max(res, 2 + dfs(i + 1, j - 1, k - t));
// }
// f[i][j][k] = res;
// return res;
// }
// }
// Accepted solution for LeetCode #3472: Longest Palindromic Subsequence After at Most K Operations
function longestPalindromicSubsequence(s: string, k: number): number {
const n = s.length;
const sCodes = s.split('').map(c => c.charCodeAt(0));
const f: number[][][] = Array.from({ length: n }, () =>
Array.from({ length: n }, () => Array(k + 1).fill(-1)),
);
function dfs(i: number, j: number, k: number): number {
if (i > j) {
return 0;
}
if (i === j) {
return 1;
}
if (f[i][j][k] !== -1) {
return f[i][j][k];
}
let res = Math.max(dfs(i + 1, j, k), dfs(i, j - 1, k));
const d = Math.abs(sCodes[i] - sCodes[j]);
const t = Math.min(d, 26 - d);
if (t <= k) {
res = Math.max(res, 2 + dfs(i + 1, j - 1, k - t));
}
return (f[i][j][k] = res);
}
return dfs(0, n - 1, k);
}
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^2 × k)
Space
O(n^2 × k)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.