LeetCode 680: Valid Palindrome II Solution

Master LeetCode problem 680 (Valid Palindrome II), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

680. Valid Palindrome II

Problem Explanation

Explanation

To solve this problem, we can use a two-pointer approach. We initialize two pointers, one at the beginning of the string and the other at the end of the string. We then compare the characters at these pointers. If they are the same, we move the pointers towards each other. If they are different, we try two possibilities:

  1. Skip the character at the left pointer and check if the remaining substring is a palindrome.
  2. Skip the character at the right pointer and check if the remaining substring is a palindrome.

If either of these possibilities results in a palindrome, we return true. If none of them result in a palindrome, we return false.

Solution Code

class Solution {
    public boolean validPalindrome(String s) {
        int left = 0, right = s.length() - 1;
        
        while (left < right) {
            if (s.charAt(left) != s.charAt(right)) {
                return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1);
            }
            left++;
            right--;
        }
        
        return true;
    }
    
    private boolean isPalindrome(String s, int start, int end) {
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 680 (Valid Palindrome II)?

This page provides optimized solutions for LeetCode problem 680 (Valid Palindrome II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 680 (Valid Palindrome II)?

The time complexity for LeetCode 680 (Valid Palindrome II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 680 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 680 in Java, C++, or Python.

Back to LeetCode Solutions