VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-there-exists-any-sub-sequence-in-a-string-which-is-not-palindrome/

⇱ Check if there exists any sub-sequence in a string which is not palindrome - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if there exists any sub-sequence in a string which is not palindrome

Last Updated : 7 May, 2025

Given a string s consisting of lowercase characters, the task is to check if there exists any subsequence in the string which is not a palindrome. If there is at least 1 such subsequence, then return true, otherwise return false.

Examples

Input : str = "abaab"
Output: Yes
Explanation: Subsequences "ab" , "abaa" , "aab", are not a palindrome.

Input : str = "zzzz"
Output: NO
Explanation: All possible subsequences are palindrome.

[Naive Approach] Checking Each Subsequence - O(2^n) time and O(n) space

The idea is to generate all possible subsequences of the given string and check each one to see if it's not a palindrome. If we find even one subsequence that is not a palindrome, we return true; otherwise, we return false.


Output
Yes

[Expected Approach] Using Hash Set - O(n) time and O(1) space

The idea is to recognize that a subsequence is not a palindrome if and only if the string contains at least two different characters. This is because any subsequence with all same characters is always a palindrome, and any subsequence with at least two different characters can be arranged to form a non-palindrome.

Step by step approach:

  1. Create a hash set to store unique characters.
  2. Iterate through each character of the string and add each character to the hash set.
  3. If the hash set size is >= 2, return true (found a non-palindrome subsequence). Otherwise, return false.

Output
Yes
Comment
Article Tags: