BackeasyTwo PointersWiproMeesho

Valid Palindromic Sequence Solution

Problem Statement

Given a string sequence, determine if it is possible to obtain a palindrome by removing at most one character.

Example 1
Input
aba
Output
false

Explanation: The input string 'aba' is already a palindrome, so no removal is needed. Therefore, the output should be false.

Example 2
Input
abca
Output
false

Explanation: Removing 'c' from 'abca' results in 'aba', which is a palindrome. However, the problem statement asks for at most one removal, and removing 'c' is not the only possible solution. Another possible solution is to remove 'a' from 'abca'. Therefore, the output should be false.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Valid Palindromic Sequence — Problem Statement & Solution Guide

Two PointersEasyTwo Pointers
TimeO(n)
|
SpaceO(1)

Problem Description

Given a string sequence, determine if it is possible to obtain a palindrome by removing at most one character.

Examples

Example 1

Input

aba

Output

false

Explanation: The input string 'aba' is already a palindrome, so no removal is needed. Therefore, the output should be false.

Example 2

Input

abca

Output

false

Explanation: Removing 'c' from 'abca' results in 'aba', which is a palindrome. However, the problem statement asks for at most one removal, and removing 'c' is not the only possible solution. Another possible solution is to remove 'a' from 'abca'. Therefore, the output should be false.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters.

Optimal Approach & Strategy

Two pointers. When s[left] != s[right], check if substring(left+1, right) is palindrome OR substring(left, right-1) is palindrome. Time O(N), Space O(1).

Brute Force Approach

Remove each character one by one and check if string becomes palindrome. Time O(N^2).

Verified Code Solutions

JavaScript Solution
Time: O(n)
function validPalindromicSequence(sequence) { if (sequence.length < 2) return true; let left = 0, right = sequence.length - 1; while (left < right) { if (sequence[left] !== sequence[right]) { if (sequence[left + 1] === sequence[right]) { left++; } else if (sequence[left] === sequence[right - 1]) { right--; } else { return false; } } else { left++; right--; } } return true; }

Asked in Top Tech Interviews

WiproMeesho

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.