Valid Palindrome IV - Problem

You are given a 0-indexed string s consisting of only lowercase English letters.

In one operation, you can change any character of s to any other character.

Return true if you can make s a palindrome after performing exactly one or two operations, or return false otherwise.

Input & Output

Example 1 — Basic Case
$ Input: s = "abcdba"
Output: true
💡 Note: Compare from ends: a=a (match), b=b (match), c≠d (1 mismatch). Total mismatches = 1 ≤ 2, so return true.
Example 2 — Two Mismatches
$ Input: s = "aa"
Output: true
💡 Note: Already a palindrome (0 mismatches), but we need exactly 1-2 operations. We can change any character to make 1 operation.
Example 3 — Too Many Mismatches
$ Input: s = "abcdef"
Output: false
💡 Note: Compare pairs: a≠f, b≠e, c≠d. That's 3 mismatches > 2, so impossible with only 1-2 operations.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of only lowercase English letters

Visualization

Tap to expand
Valid Palindrome IV: Can "abcde" become palindrome with 1-2 changes?Input String:abcdeCompare Pairs:a ≠ e (mismatch 1)b ≠ d (mismatch 2)c in middle (no pair)Analysis:Total mismatches = 2 ≤ 2 operations allowedOutput: true
Understanding the Visualization
1
Input
String s that we want to make palindrome
2
Count Mismatches
Compare characters from both ends, count differences
3
Decision
Return true if ≤2 mismatches (can fix with 1-2 operations)
Key Takeaway
🎯 Key Insight: Count mismatches from both ends - if ≤2, we can make palindrome with 1-2 operations
Asked in
Facebook 35 Amazon 28 Microsoft 22
28.0K Views
Medium Frequency
~15 min Avg. Time
850 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