Longest Palindromic Subsequence After at Most K Operations - Problem

You're given a string s and an integer k. Your goal is to find the longest palindromic subsequence possible after performing at most k character transformations.

In each operation, you can transform any character to its next or previous letter in the alphabet (with wraparound). For example:

  • 'a''b' (next) or 'a''z' (previous)
  • 'z''a' (next) or 'z''y' (previous)
  • 'm''n' (next) or 'm''l' (previous)

Key insight: You need to strategically use your k operations to create the longest possible palindromic subsequence. Remember, a subsequence doesn't need to be contiguous, but it must maintain the original relative order of characters.

Input & Output

example_1.py — Basic transformation
$ Input: s = "abcd", k = 2
Output: 4
💡 Note: We can transform 'a'→'d' (cost: min(3,23)=3 > k) or 'b'→'c' (cost: 1 ≤ k). Better approach: transform 'a'→'b' (cost: 1) and 'd'→'c' (cost: 1), making "bbcc". The longest palindromic subsequence is "bccb" with length 4.
example_2.py — Wraparound case
$ Input: s = "aaa", k = 1
Output: 3
💡 Note: The string is already "aaa", which is itself a palindrome. No operations needed, so the longest palindromic subsequence has length 3.
example_3.py — Limited operations
$ Input: s = "abc", k = 0
Output: 1
💡 Note: With k=0, no transformations are allowed. The original string "abc" has no repeated characters, so the longest palindromic subsequence is any single character, giving length 1.

Constraints

  • 1 ≤ s.length ≤ 1000
  • 0 ≤ k ≤ 1000
  • s consists only of lowercase English letters
  • Time limit: 2 seconds per test case

Visualization

Tap to expand
Palindrome Formation StrategyInput: "abcd", k=2Original string:abcdTransformation costs:a ↔ d: min(3, 23) = 3b ↔ c: min(1, 25) = 1✓ b↔c fits in budget k=2Strategy: Transform b→c and d→cacb→cccd→cResulting palindromic subsequence:ccccLength: 4Cost: 1 (b→c) + 1 (d→c) = 2 ≤ k
Understanding the Visualization
1
Identify potential pairs
Look at characters from both ends that could form palindromic pairs
2
Calculate transformation costs
For each pair, find the minimum operations needed to make them identical
3
Choose optimal strategy
Decide whether to transform pairs or skip characters based on operation budget
4
Build longest palindrome
Construct the longest possible palindromic subsequence within constraints
Key Takeaway
🎯 Key Insight: Calculate minimum circular alphabet distance between character pairs and use dynamic programming to find the optimal combination of transformations within the operation budget.
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
28.5K Views
Medium Frequency
~25 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen