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 INPUT String s = "abcdba" a 0 b 1 c 2 d 3 b 4 a 5 Two Pointer Approach left right Compare: s[i] vs s[n-1-i] Count mismatches Input: s = "abcdba" ALGORITHM STEPS 1 Initialize Set mismatch count = 0 2 Compare Pairs s[0]=a vs s[5]=a [OK] 3 Continue Check s[1]=b vs s[4]=b [OK] 4 Find Mismatch s[2]=c vs s[3]=d [DIFF] Mismatch Count: 1 c != d at positions 2,3 1 <= 2 operations needed if mismatches <= 2: return true FINAL RESULT After 1 operation: a b d d b a "abddba" is a palindrome! Palindrome Verification a = a [OK] b = b [OK] d = d [OK] Output: true Only 1 mismatch found 1 <= 2 operations allowed Palindrome achievable! Key Insight: For a string to become a palindrome with at most 2 operations, we only need to count mismatched pairs. Each mismatch at positions (i, n-1-i) can be fixed with 1 operation. Time: O(n) | Space: O(1) - Compare pairs from outside inward, count differences. TutorialsPoint - Valid Palindrome IV | Optimal Solution
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