Tutorialspoint
Problem
Solution
Submissions

Valid Palindrome II

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 8

Write a JavaScript program to determine if a string can be a palindrome after removing at most one character from it. A palindrome reads the same forwards and backwards.

Example 1
  • Input: s = "aba"
  • Output: true
  • Explanation:
    • The string "aba" is already a palindrome.
    • No character removal is needed.
    • Therefore, it's valid with at most one character removal.
Example 2
  • Input: s = "abca"
  • Output: true
  • Explanation:
    • The string "abca" is not a palindrome initially.
    • If we remove character 'c' at index 2, we get "aba".
    • The string "aba" is a palindrome.
    • Therefore, removing one character makes it a valid palindrome.
Constraints
  • 1 ≤ s.length ≤ 10^5
  • s consists only of lowercase English letters
  • At most one character can be removed
  • Time Complexity: O(n)
  • Space Complexity: O(1)
StringsWiproShopify
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use two pointers approach starting from both ends of the string
  • If characters at both pointers match, move both pointers inward
  • If characters don't match, try removing either the left or right character
  • Check if the remaining substring is a palindrome after removal
  • Create a helper function to check if a substring is a palindrome
  • Return true if removing one character results in a palindrome, false otherwise

Steps to solve by this approach:

 Step 1: Initialize two pointers, left at the beginning and right at the end of the string.
 Step 2: Compare characters at left and right pointers while moving them toward each other.
 Step 3: If characters match, increment left pointer and decrement right pointer.
 Step 4: If characters don't match, we have found a mismatch point.
 Step 5: Try two possibilities: remove the left character or remove the right character.
 Step 6: Check if either of the remaining substrings forms a palindrome using helper function.
 Step 7: Return true if the string is already a palindrome or if removing one character makes it palindrome.

Submitted Code :